-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Construct Binary Tree from Preorder and Inorder Traversal Solution
- Loading branch information
jinbeom
committed
Aug 24, 2024
1 parent
d3c9643
commit 713cfed
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
construct-binary-tree-from-preorder-and-inorder-traversal/kayden.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# 시간복잡도: O(N) | ||
# 공간복잡도: O(N) | ||
class TreeNode: | ||
def __init__(self, val=0, left=None, right=None): | ||
self.val = val | ||
self.left = left | ||
self.right = right | ||
|
||
|
||
class Solution: | ||
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: | ||
|
||
mapping = {} | ||
|
||
for i in range(len(inorder)): | ||
mapping[inorder[i]] = i | ||
|
||
preorder = collections.deque(preorder) | ||
|
||
def build(start, end): | ||
if start > end: return None | ||
|
||
root = TreeNode(preorder.popleft()) | ||
mid = mapping[root.val] | ||
|
||
root.left = build(start, mid - 1) | ||
root.right = build(mid + 1, end) | ||
|
||
return root | ||
|
||
return build(0, len(preorder) - 1) |