Skip to content

Commit 2d4eff0

Browse files
author
Joseph Luce
authored
Create 105_construct_binary_tree_from_preorder_and_inorder_traversal.md
1 parent f14ae04 commit 2d4eff0

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 105. Construct Binary Tree from Preorder and Inorder 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+
The preorder traversal is the pinnacle element.
9+
Without the preorder traversal, we will not be able to construct a binary tree given any combination of the other traversals.
10+
The property to be able to find the root node of the preorder traversal is key.
11+
12+
Given preorder of [A,B,D,E,C,F,G] and inorder of [D,B,E,A,F,C,G].
13+
Using the preorder, we can see that A is the root of the entire tree.
14+
Using A, looking at the inorder we know that the left-subtree is [D,B,E] and the right-subtree is [F,C,G].
15+
Going back to the preorder with this information, we can see that [B,D,E] is our left-subtree, and [C,F,G] is our right.
16+
17+
Now we can then use recursion to further build the nodes, we can take preorder [B,D,E] and inorder [D,B,E] to build the left-subtree, to similar effect with the right as well.
18+
Using the same rules applied above, we know B is the root node and [D] is on the left and [E] is on the right.
19+
20+
To find the associated index of the inorder value using the preorder value would take O(N), however, using an enumerated hash table can make this O(1).
21+
22+
```
23+
class Solution:
24+
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
25+
26+
def build_helper(preorder_start, preorder_end, inorder_start, inorder_end):
27+
if preorder_start > preorder_end or inorder_start > inorder_end:
28+
return None
29+
inorder_root_idx = val_to_inorder_idx[preorder[preorder_start]]
30+
left_size = inorder_root_idx - inorder_start
31+
node = TreeNode(preorder[preorder_start])
32+
node.left = build_helper(preorder_start+1, preorder_start+1+left_size, inorder_start, inorder_root_idx-1)
33+
node.right = build_helper(preorder_start+1+left_size, preorder_end, inorder_root_idx+1, inorder_end)
34+
return node
35+
36+
val_to_inorder_idx = {val: i for i, val in enumerate(inorder)}
37+
return build_helper(0, len(preorder)-1, 0, len(inorder)-1)
38+
```

0 commit comments

Comments
 (0)