|
| 1 | +# 106. Construct Binary Tree from Inorder and Postorder Traversal |
| 2 | + |
| 3 | +## Recursive Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) (Due to hash table) |
| 6 | +- N = Number of elements in list |
| 7 | + |
| 8 | +Similar to question 105. |
| 9 | +Postorder allows us to know which is the root node by using the last element of the array. |
| 10 | +With this, we can figure out the left and right sub-trees in the inorder traversal. |
| 11 | +Using recursion, we can continue to break up the sub-trees once we know which is the root of the sub-tree using this method. |
| 12 | + |
| 13 | +To allow for quicker look ups for roots, we can build an enmuerated hash table to find the indexes for each value of the inorder traversal. |
| 14 | + |
| 15 | +``` |
| 16 | +class Solution: |
| 17 | + def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: |
| 18 | + |
| 19 | + def build_helper(inorder_start, inorder_end, postorder_start, postorder_end): |
| 20 | + if inorder_start > inorder_end or postorder_start > postorder_end: |
| 21 | + return None |
| 22 | + inorder_root_idx = val_to_inorder_idx[postorder[postorder_end]] |
| 23 | + right_size = inorder_end - inorder_root_idx |
| 24 | + node = TreeNode(postorder[postorder_end]) |
| 25 | + node.left = build_helper(inorder_start, inorder_root_idx-1, postorder_start, postorder_end - right_size - 1) |
| 26 | + node.right = build_helper(inorder_root_idx + 1, inorder_end, postorder_end - right_size, postorder_end - 1) |
| 27 | + return node |
| 28 | + |
| 29 | + val_to_inorder_idx = {val: i for i, val in enumerate(inorder)} |
| 30 | + return build_helper(0, len(inorder)-1, 0, len(postorder)-1) |
| 31 | +``` |
0 commit comments