Beispiel #1
0
 def solution(self, answerList):
     if (answerList == None):
         return
     else:
         middle = answerList[len(answerList) // 2]
         left = answerList[:len(answerList) // 2]
         right = answerList[(len(answerList) // 2) + 1:]
         obj = BST()
         obj.addNode(obj.root, middle)
         for l in left:
             obj.addNode(obj.root, l)
         for r in right:
             obj.addNode(obj.root, r)
         # obj.inOrder(obj.root)
         # print("Height of tree:",obj.getHeightOfTree(obj.root))
         return obj
Beispiel #2
0
def keyNodeInT1(root, key):
    if root == None:
        return None

    left = keyNodeInT1(root.left, key)
    right = keyNodeInT1(root.right, key)

    if (left != None):
        if (left.data == key):
            return left

    if (right != None):
        if (right.data == key):
            return right

    return root


if __name__ == '__main__':
    createtree = BST()
    nodes = [10, 5, 30, 4, 25, 35, 1, 20, 23, 32, 40, 0, 2]
    node1 = [1, 0, 2]
    createSubtree = BST()
    for n in node1:
        createSubtree.addNode(createSubtree.root, n)
    for n in nodes:
        createtree.addNode(createtree.root, n)
    # createtree.inOrder(createtree.root)
    keyNode = keyNodeInT1(createtree.root, 1)  # return closest node
    print("keynode found: ", keyNode.data)
    print(checkSubTree(keyNode, createSubtree.root))
Beispiel #3
0

def weaveLists(left, right, results, prefix):
    if (len(left) == 0):
        result = prefix.copy()
        result.append(left)
        results.append(result)
        return
    else:
        result = prefix.copy()
        result.append(right)
        results.append(result)
        return

    headFirst = left.removeFirst()
    weaveLists(left, right, results, prefix)
    prefix.removeLast()
    left.addFirst(headFirst)

    headsecond = right.removeFirst()
    weaveLists(right, right, results, prefix)
    prefix.removeLast()
    right.addFirst(headsecond)


if __name__ == '__main__':
    treeObj = BST()
    numberList = [50, 30, 100, 20, 35, 200, 40, 150]
    for number in numberList:
        treeObj.addNode(treeObj.root, number)
Beispiel #4
0
    if (root == None):
        return -1

    left = getHeight(root.left)

    if (left == float('-inf')):
        return float('-inf')

    right = getHeight(root.right)
    if (right == float('-inf')):
        return float('-inf')

    if (abs(left - right) > 1):
        return float('-inf')
    else:
        return max(left, right) + 1


def checkBalanced(root):
    print(getHeight(root))
    return getHeight(root) != float('-inf')


if __name__ == '__main__':
    createTree = BST()

    elements = [4, 6, 5, 3, 2, 9, 1]
    for e in elements:
        createTree.addNode(createTree.root, e)
    # tree = createTree.solution([1,2,3,4,6,5])
    print(checkBalanced(createTree.root))