Skip to content

Commit eb41706

Browse files
committed
solve: construct binary tree from preorder and inorder traversal
1 parent 6e19022 commit eb41706

File tree

1 file changed

+37
-0
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import List, Optional
2+
3+
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
11+
class Solution:
12+
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
13+
if not preorder or not inorder:
14+
return None
15+
16+
root_val = preorder.pop(0)
17+
18+
root_inorder_index = inorder.index(root_val)
19+
20+
left_tree_inorder = inorder[:root_inorder_index]
21+
right_tree_inorder = inorder[root_inorder_index + 1 :]
22+
23+
return TreeNode(
24+
root_val,
25+
self.buildTree(preorder, left_tree_inorder),
26+
self.buildTree(preorder, right_tree_inorder),
27+
)
28+
29+
30+
# Overall time complexity: O(N^2)
31+
# - Finding the root in the inorder list and splitting it takes O(N) time in each call.
32+
# - There are N nodes, so this operation is repeated N times.
33+
34+
# Overall space complexity: O(N)
35+
# - The primary space usage is the recursion stack which goes as deep as the height of the tree.
36+
# - In the worst case (unbalanced tree), this can be O(N).
37+
# - In the best case (balanced tree), this is O(log N).

0 commit comments

Comments
 (0)