Skip to content

Commit 713cfed

Browse files
author
jinbeom
committed
Construct Binary Tree from Preorder and Inorder Traversal Solution
1 parent d3c9643 commit 713cfed

File tree

1 file changed

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

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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)

0 commit comments

Comments
 (0)