File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List , Optional
2+
3+ # Definition for a binary tree node.
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+ class Solution :
11+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
12+ inorder_map = {value : idx for idx , value in enumerate (inorder )}
13+ self .preorder_idx = 0
14+
15+ def helper (left : int , right : int ) -> Optional [TreeNode ]:
16+ if left > right :
17+ return None
18+
19+ root_val = preorder [self .preorder_idx ]
20+ self .preorder_idx += 1
21+
22+ root = TreeNode (root_val )
23+ root .left = helper (left , inorder_map [root_val ] - 1 )
24+ root .right = helper (inorder_map [root_val ] + 1 , right )
25+
26+ return root
27+
28+ return helper (0 , len (inorder ) - 1 )
29+
30+
31+ # Time Complexity: O(n)
32+ # - Each node is visited exactly once in preorder, and the dictionary lookup in inorder_map takes O(1) per node.
33+
34+ # Space Complexity: O(n)
35+ # - The hash map (inorder_map) uses O(n) space.
36+ # - The recursion stack uses up to O(h) space, where h is the height of the tree (O(n) in the worst case, O(log n) for a balanced tree).
You can’t perform that action at this time.
0 commit comments