""" An iterative solution with O(N) time complexity and O(1) space complexity """ node = root while node: if n1.val > node.val and n2.val > node.val: node = node.right elif n1.val < node.val and n2.val < node.val: node = node.left else: return node # -- Testing from random import randint, seed if __name__ == "__main__": seed(69) tree = TreeNode(50) for _ in range(25): tree.insert(randint(0, 100)) tree.display() print('---') node0, node1 = tree.search(41), tree.search(56) print(f'Nodes: {node0} {node1}') print(f'LCA: {lca(tree, node0, node1)}') print(f'LCA: {lowest_common_ancestor(tree, node0, node1)}')
if not T1 and not T2: return True # One empty if not T1 or not T2: return False # Non-equal values if T1.val != T2.val: return False # Otherwise, check that subtrees are equivalent return is_equal(T1.left, T2.left) and is_equal(T1.right, T2.right) # -- Testing from random import randint, seed if __name__ == "__main__": seed(1209) T1 = TreeNode(50) for _ in range(50): T1.insert(randint(0, 100)) T1.display() T2 = T1.search(42) T2.display() print(check_subtree(T1, T2))