From 97eb6f9759f08484a9e0b52a458dc61c3e24cdad Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sun, 22 Dec 2024 12:35:55 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20add=20Solution=20for=20=EC=B5=9C?= =?UTF-8?q?=EC=A0=81=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Chaedie.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/Chaedie.py b/construct-binary-tree-from-preorder-and-inorder-traversal/Chaedie.py index 7432a4100..8587dd26a 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/Chaedie.py +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/Chaedie.py @@ -27,3 +27,31 @@ def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNod newNode.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) return newNode + +''' +알고달레 참고해서 최적화 진행했습니다. +1) 시간복잡도 최적화: dictionary 를 활용해 mid 를 찾는 index 메서드 제거 +2) 공간복잡도 최적화: preorder, inorder 배열을 넘기는것이 아닌 index 만 넘김 + +Time: O(n) +Space: O(n) + +''' + +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: + indices = { val: idx for idx, val in enumerate(inorder) } + pre_iter = iter(preorder) + + def dfs(start, end): + if start > end: + return None + + val = next(pre_iter) + mid = indices[val] + + left = dfs(start, mid - 1) + right = dfs(mid + 1, end) + return TreeNode(val, left, right) + + return dfs(0, len(inorder) - 1)