return False return Check(T1.leftChild, T2.leftChild) and Check(T1.rightChild, T2.rightChild) # Testing part... T8_0 = BinarySearchTree() T8_1 = BinarySearchTree() T8_2 = BinarySearchTree() print "Tree 0:" list0 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] T8_0.root = miniHeightBST(list0, 0, len(list0) - 1) T8_0.root.printSubtree(5) list1 = [2, 1, 3, 4] for i in list1: T8_1.insertion(i) print "Tree 1: " T8_1.root.printSubtree(5) print "Tree 2:" list2 = [8, 6, 7] for j in list2: T8_2.insertion(j) T8_2.root.printSubtree(5) print "----------Checking-----------" print "T1 is a subtree of T0 should be True: " + (containTree(T8_0.root, T8_1.root) and "True" or "False") print "T2 is a subtree of T0 should be False: " + (containTree(T8_0.root, T8_2.root) and "True" or "False")
difference = abs((leftHeight-rightHeight)) if(difference > 1): return -1 else: return max(leftHeight,rightHeight) + 1 def checkBalance(root): if(checkHeight(root) == -1): print "The tree is not balanced!" else: print "The height of tree is: " + str(checkHeight(root)) # Testing Part... balance = [5,3,2,4,6] unbalance = [5,3,2,4,6,1] T1 = BinarySearchTree() T2 = BinarySearchTree() for i in balance: T1.insertion(i) T1.root.printSubtree(5) for i in unbalance: T2.insertion(i) T2.root.printSubtree(5) checkBalance(T1.root) checkBalance(T2.root)
while(buffer.isEmpty() is False): node = buffer.peek() if(node.rightChild != None and node.rightChild.visited is False): # We have to set a visited flag that make the node = node.rightChild # nodes will not visit multiple times. while(node != None): buffer.push(node) parent = node node = node.leftChild if(parent.rightChild == None): arraylist.append(parent.key) parent.visited = True buffer.pop() else: node.visited = True # Set visited flags arraylist.append(node.key) buffer.pop() return arraylist #Testing part... TreeRoot = BinarySearchTree() Treelist = [10,5,3,4,7,6,8,11,12,9] for i in Treelist: TreeRoot.insertion(i) TreeRoot.root.printSubtree(5) result = postOrderTraversial(TreeRoot.root) print result
if(node.rightChild != None): node = node.rightChild while(node.leftChild != None): node = node.leftChild return node else: current = node parent = node.parent while(parent != None and parent.leftChild != current): current = parent parent = current.parent return parent # Testing Part... T6 = BinarySearchTree() Treelist = [10,5,3,4,7,6,8,11] for i in Treelist: T6.insertion(i) T6.root.printSubtree(5) print "The in order successor of node 7 should be 8: " + \ str(findInorderSuccessor(T6.root.leftChild.rightChild).key) print "The in order successor of node 4 should be 5: " + \ str(findInorderSuccessor(T6.root.leftChild.leftChild.rightChild).key)