File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 시간복잡도: O(N)
2
+ # 공간복잡도: O(N)
3
+ class TreeNode :
4
+ def __init__ (self , val = 0 , left = None , right = None ):
5
+ self .val = val
6
+ self .left = left
7
+ self .right = right
8
+
9
+
10
+ class Solution :
11
+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
12
+
13
+ mapping = {}
14
+
15
+ for i in range (len (inorder )):
16
+ mapping [inorder [i ]] = i
17
+
18
+ preorder = collections .deque (preorder )
19
+
20
+ def build (start , end ):
21
+ if start > end : return None
22
+
23
+ root = TreeNode (preorder .popleft ())
24
+ mid = mapping [root .val ]
25
+
26
+ root .left = build (start , mid - 1 )
27
+ root .right = build (mid + 1 , end )
28
+
29
+ return root
30
+
31
+ return build (0 , len (preorder ) - 1 )
You can’t perform that action at this time.
0 commit comments