From 135c6bd58a260d490b89baa1e437a37b05da8fe3 Mon Sep 17 00:00:00 2001 From: bt3gl <138340846+cypher-bt3gl@users.noreply.github.com> Date: Sat, 29 Jul 2023 15:49:16 -0700 Subject: [PATCH] Create construct_tree.py --- trees_and_graphs/construct_tree.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 trees_and_graphs/construct_tree.py diff --git a/trees_and_graphs/construct_tree.py b/trees_and_graphs/construct_tree.py new file mode 100644 index 0000000..a1fec27 --- /dev/null +++ b/trees_and_graphs/construct_tree.py @@ -0,0 +1,25 @@ +# Given two integer arrays inorder and postorder where inorder is the inorder +# traversal of a binary tree and postorder is the postorder traversal of the +# same tree, construct and return the binary tree. + +def build_tree(inorder: list[int], postorder: list[int]) -> Optional[TreeNode]: + + def fill_tree(i_left, i_right, inorder_map): + + if i_left > i_right: + return None + + val = postorder.pop() + root = TreeNode(val) + + index_here = inorder_map[val] + + root.right = fill_tree(index_here + 1, i_right, inorder_map) + root.left = fill_tree(i_left, index_here - 1, inorder_map) + + return root + + inorder_map = {val: index for index, val in enumerate(inorder)} + + return fill_tree(0, len(inorder) - 1, inorder_map) +