File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for a binary tree node.
2
+ # class TreeNode:
3
+ # def __init__(self, val=0, left=None, right=None):
4
+ # self.val = val
5
+ # self.left = left
6
+ # self.right = right
7
+ class Solution :
8
+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
9
+ """
10
+ Intuition:
11
+ preorder 트리의 첫번째 원소는 항상 루트이다.
12
+ 또한, inorder 트리에서 루트를 기준으로 왼쪽은 left child,
13
+ 오른쪽은 right child를 의미한다.
14
+ 따라서 이를 이용해 재귀적으로 호출한다.
15
+
16
+ Time Complexity:
17
+ O(N^2):
18
+ parent_idx를 선택하는 데에 O(N)이 소요되고
19
+ 최악의 경우 N번 재귀 호출해야 하므로 O(N^2)이다.
20
+
21
+ Space Complexity:
22
+ O(N):
23
+ TreeNode는 N개의 값을 저장한다.
24
+
25
+ Key takeaway:
26
+ 리트코드에서 클래스를 반환하는 문제는 다음처럼 하는 것을
27
+ 처음 알게 되었다.
28
+ """
29
+ if not preorder :
30
+ return None
31
+
32
+ parent = preorder [0 ]
33
+ parent_idx = inorder .index (parent ) # O(N)
34
+
35
+ left_pre = preorder [1 :parent_idx + 1 ]
36
+ left_in = inorder [:parent_idx ]
37
+ left = self .buildTree (left_pre , left_in )
38
+
39
+ right_pre = preorder [1 + parent_idx :]
40
+ right_in = inorder [1 + parent_idx :]
41
+ right = self .buildTree (right_pre , right_in )
42
+
43
+ tree = TreeNode (parent , left , right )
44
+
45
+ return tree
You can’t perform that action at this time.
0 commit comments