def MinimalTree(A: List[int]) -> Node: if not A: return None lenA = len(A) if lenA == 1: return Node(A[0]) root = Node(A[lenA // 2]) root.left = MinimalTree(A[: lenA // 2]) root.right = MinimalTree(A[lenA // 2 :]) return root
def maketree3(preorder, postorder): if len(preorder) == 0 or len(postorder) == 0: return None rootVal = postorder[-1] rChildIndex = preorder.index(postorder[-2]) lpreorder = filter(lambda x: preorder.index(x) < rChildIndex, preorder) rpreorder = filter(lambda x: preorder.index(x) >= rChildIndex, preorder) lpostorder = filter(lambda x: x in lpreorder, postorder) rpostorder = filter(lambda x: x in rpreorder, postorder) root = Node(rootVal) root.left = maketree3(lpreorder, lpostorder) root.right = maketree3(rpreorder, rpostorder) return root
def maketree2(postorder, inorder): if len(postorder) == 0 or len(inorder) == 0: return None rootVal = postorder[-1] rootIndex = inorder.index(rootVal) linorder = filter(lambda x: inorder.index(x) < rootIndex, inorder) rinorder = filter(lambda x: inorder.index(x) > rootIndex, inorder) lpostorder = filter(lambda x: x in linorder, postorder) rpostorder = filter(lambda x: x in rinorder, postorder) root = Node(rootVal) root.left = maketree2(lpostorder, linorder) root.right = maketree2(rpostorder, rinorder) return root
#simple binary tree from treeNode import Node if __name__ == "__main__": ROOT = Node(1) ROOT.left = Node(2) ROOT.right = Node(3) print(ROOT.val) print(ROOT.left.val) print(ROOT.right.val)
# to store distance of n2 from lca d2 = [] # if lca exist if lca: # distance of n1 from lca findLevel(lca, n1, d1, 0) # distance of n2 from lca findLevel(lca, n2, d2, 0) return d1[0] + d2[0] else: return -1 # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) root.display() # root.prettyPrint() print("Dist(4,5) = ", findDistance(root, 4, 5)) print("Dist(4,6) = ", findDistance(root, 4, 6)) print("Dist(3,4) = ", findDistance(root, 3, 4)) print("Dist(2,4) = ", findDistance(root, 2, 4)) print("Dist(8,5) = ", findDistance(root, 8, 5))