Skip to content

Commit

Permalink
Construct Binary Tree from Preorder and Inorder Traversal Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jinbeom committed Aug 24, 2024
1 parent d3c9643 commit 713cfed
Showing 1 changed file with 31 additions and 0 deletions.
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)

0 comments on commit 713cfed

Please sign in to comment.