Skip to content

Commit 7e6495f

Browse files
Solve : Construct Binary Tree from Preorder and Inorder Traversal
1 parent d1907a1 commit 7e6495f

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def buildTree(self, preorder, inorder):
3+
inorder_index_map = {val: idx for idx, val in enumerate(inorder)}
4+
def build(pre_left, pre_right, in_left, in_right):
5+
if pre_left > pre_right:
6+
return None
7+
root_val = preorder[pre_left]
8+
root = TreeNode(root_val)
9+
in_root_idx = inorder_index_map[root_val]
10+
left_size = in_root_idx - in_left
11+
root.left = build(pre_left + 1, pre_left + left_size, in_left, in_root_idx - 1)
12+
root.right = build(pre_left + left_size + 1, pre_right, in_root_idx + 1, in_right)
13+
return root
14+
return build(0, len(preorder) - 1, 0, len(inorder) - 1)

0 commit comments

Comments
 (0)