Skip to content

Commit 211cf45

Browse files
committed
Solve Construct Binary Tree from Preorder and Inorder Traversal
1 parent ffc2d48 commit 211cf45

File tree

1 file changed

+29
-12
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+29
-12
lines changed

construct-binary-tree-from-preorder-and-inorder-traversal/KwonNayeon.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,36 @@
11
"""
22
Constraints:
3-
1. 1 <= preorder.length <= 3000
4-
2. inorder.length == preorder.length
5-
3. -3000 <= preorder[i], inorder[i] <= 3000
6-
4. preorder and inorder consist of unique values
7-
5. Each value of inorder also appears in preorder
8-
6. preorder is guaranteed to be the preorder traversal of the tree
9-
7. inorder is guaranteed to be the inorder traversal of the tree
3+
1. 1 <= preorder.length <= 3000
4+
2. inorder.length == preorder.length
5+
3. -3000 <= preorder[i], inorder[i] <= 3000
6+
4. preorder and inorder consist of unique values
7+
5. Each value of inorder also appears in preorder
8+
6. preorder is guaranteed to be the preorder traversal of the tree
9+
7. inorder is guaranteed to be the inorder traversal of the tree
1010
11-
Time Complexity:
12-
- O(N^2). 각 노드(N)마다 inorder에서 index를 찾는 연산(N)이 필요하고, 각 노드를 한 번씩 방문하여 트리를 구성하기 때문.
13-
Space Complexity:
14-
- O(N). 재귀 호출 스택을 위한 공간이 필요하며, 최악의 경우(한쪽으로 치우친 트리) 재귀 깊이가 N까지 갈 수 있기 때문.
15-
"""
11+
Time Complexity: O(N^2)
12+
- 각 노드(N)마다 inorder에서 index를 찾는 연산(N)이 필요하고, 각 노드를 한 번씩 방문하여 트리를 구성하기 때문.
13+
Space Complexity: O(N)
14+
- 재귀 호출 스택을 위한 공간이 필요하며, 최악의 경우(한쪽으로 치우친 트리) 재귀 깊이가 N까지 갈 수 있기 때문.
15+
16+
아이디어:
17+
- preorder: 루트의 위치를 알려줌
18+
- inorder: 왼쪽/오른쪽 서브트리를 구분해줌
1619
20+
풀이방법:
21+
1. 빈 배열일 때 None 반환
22+
2. root, mid 변수 생성 (mid - 왼쪽/오른쪽 서브트리 경계)
23+
3. 재귀를 활용하여 서브트리 분할
24+
25+
예시:
26+
- Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
27+
"""
28+
# Definition for a binary tree node.
29+
# class TreeNode:
30+
# def __init__(self, val=0, left=None, right=None):
31+
# self.val = val
32+
# self.left = left
33+
# self.right = right
1734
class Solution:
1835
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
1936
if not preorder or not inorder:

0 commit comments

Comments
 (0)