def minHeightTree (array): mid = len(array) // 2 tree = BinaryTree() root = Node(array.pop(mid)) self.root = root for nums in array: tree.insert(nums)
def test_insert_method_for_BT(): bt = BinaryTree(BinaryTree.build(SIMPLE_TREE)) for use_case, *expected_result in [ (1, True, True, """ -- 8 | |-- 4 | | |-- 2 | | | |-- 1 | | |-- 6 | |-- 10 | | |-- 20"""), (0, True, True, """ -- 8 | |-- 4 | | |-- 2 | | | |-- 1 | | | |-- 0 | | |-- 6 | |-- 10 | | |-- 20"""), (3, True, True, """ -- 8 | |-- 4 | | |-- 2 | | | |-- 1 | | | | |-- 3 | | | |-- 0 | | |-- 6 | |-- 10 | | |-- 20"""), (8, False, True, """ -- 8 | |-- 4 | | |-- 2 | | | |-- 1 | | | | |-- 3 | | | |-- 0 | | |-- 6 | |-- 10 | | |-- 20"""), ]: insert_result, find_result, tree_repr = expected_result result = bt.insert(use_case) assert result == insert_result, "{} != {}".format(result, insert_result) result = bt.find(use_case) assert result == find_result, "{} != {}".format(result, find_result) assert str(bt) == tree_repr, "{} != {}".format(str(bt), tree_repr)
if not parent: return None return parent # 4.7 def common_ancestor(node,p,q): if not node: return (None,None,None) left = common_ancestor(node.left,p,q) right = common_ancestor(node.right,p,q) new_p = left[0] or right[0] or (node if node == p else None) new_q = left[1] or right[1] or (node if node == q else None) result = left[2] or right[2] return (new_p, new_q, node if new_p and new_q and not result else result) t = BinaryTree() t.insert(5) t.insert(2) t.insert(1) t.insert(3) t.insert(20) t.insert(21) t.insert(22) common_ancestor(t.root, t.root.left.left, t.root.left.right)[2] common_ancestor(t.root, t.root.right.right, t.root.right.right.right)[2] common_ancestor(t.root, t.root.right.right, Node(12))[2] # 4.8 # not tested except on a single tree selecting subnodes to match def subtree(n1,n2):
def tree(): tree_two = BinaryTree() nums = [45, 32, 64, 80, 21, 17, 55, 97, 33, 42, 29] for i in nums: tree_two.insert(i) return tree_two