From 713cfed80fddd2b545b35d08efeed0ac8f57dafd Mon Sep 17 00:00:00 2001 From: jinbeom Date: Sat, 24 Aug 2024 14:11:03 +0900 Subject: [PATCH] Construct Binary Tree from Preorder and Inorder Traversal Solution --- .../kayden.py | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 construct-binary-tree-from-preorder-and-inorder-traversal/kayden.py diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/kayden.py b/construct-binary-tree-from-preorder-and-inorder-traversal/kayden.py new file mode 100644 index 000000000..a30c09d9f --- /dev/null +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/kayden.py @@ -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)