if in_iter == 0: node.data = arr[1] elif in_iter == l - 1: node.data = arr[l - 2] else: node.data = arr[in_iter - 1] + arr[in_iter + 1] in_iter += 1 traverse_inorder(node.right, fill_array) arr: list = [] traverse_inorder(root, fill_array=True) in_iter = 0 l = len(arr) traverse_inorder(root, fill_array=False) return root if __name__ == "__main__": 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) print(inorder(root)) root = replace_data(root) print(inorder(root))
def full_binary_tree(preorder: list, mirror: list) -> Optional[Node]: d = {k: v for v, k in enumerate(mirror)} def tree(start: int, end: int) -> Optional[Node]: nonlocal pre_index if start > end or pre_index >= l: return None node = Node(preorder[pre_index]) pre_index += 1 if start == end or pre_index >= l: return node mirror_index = d[preorder[pre_index]] if mirror_index <= end: node.left = tree(mirror_index, end) node.right = tree(start + 1, mirror_index - 1) return node l = len(preorder) pre_index = 0 return tree(0, l - 1) if __name__ == "__main__": print(inorder(full_binary_tree([1, 2, 4, 5, 3, 6, 7], [1, 3, 7, 6, 2, 5, 4])))
nonlocal pre_index if pre_index >= l or start > end: return None value = preorder[pre_index] node = Node(value) pre_index += 1 if start == end or pre_index >= l: return node post_index: int = d[preorder[pre_index]] if post_index <= end: node.left = tree(start, post_index) node.right = tree(post_index + 1, end) return node l = len(preorder) pre_index = 0 return tree(0, l - 1) if __name__ == "__main__": print( inorder( full_binary_tree([1, 2, 4, 8, 9, 5, 3, 6, 7], [8, 9, 4, 5, 2, 6, 7, 3, 1])))
Facts: 1. Full binary tree i.e. 0 or 2 children 2. pre_ln will indicate whether the node has children time complexity: O(n) space complexity: O(n) # stack """ def tree() -> Optional[Node]: nonlocal index if index >= l: return None node = Node(preorder[index]) index += 1 if pre_ln[index - 1] == "N": node.left = tree() node.right = tree() return node index: int = 0 l: int = len(preorder) return tree() if __name__ == "__main__": print(inorder(special_tree([10, 30, 20, 5, 15], ["N", "N", "L", "L", "L"])))
""" d = {k: v for v, k in enumerate(inorder)} def tree(start: int, end: int) -> Optional[Node]: nonlocal pre_index if pre_index >= l or start > end: return None value = preorder[pre_index] node = Node(value) in_index = d.get(value) or -1 pre_index += 1 if start < end: node.left = tree(start, in_index - 1) node.right = tree(in_index + 1, end) return node l: int = len(inorder) pre_index = 0 return tree(0, l - 1) if __name__ == "__main__": inorder( construct_tree(["D", "B", "E", "A", "F", "C"], ["A", "B", "D", "E", "C", "F"]) )