|
| 1 | +# Definition for a binary tree node. |
| 2 | +# class TreeNode: |
| 3 | +# def __init__(self, val=0, left=None, right=None): |
| 4 | +# self.val = val |
| 5 | +# self.left = left |
| 6 | +# self.right = right |
| 7 | + |
| 8 | +# preorder -> root, left, right |
| 9 | +# inorder -> left, root, right |
| 10 | + |
| 11 | +# Ex1 [3,9,20,null,null,15,7] |
| 12 | +# preorder -> root-1, left, (root-2 - root, left, right) |
| 13 | +# inorder -> left, root-1, (root-2 - left, root, right) |
| 14 | + |
| 15 | +# Ex2 [-1] |
| 16 | +# preorder -> root, left(x), right(x) |
| 17 | +# inorder -> left(x), root, right(x) |
| 18 | + |
| 19 | +# Ex3 [3,9,20,11,8,15,7] |
| 20 | +# preorder -> root-1, (root-2(left) - root, left, right), (root-3(right) - root, left, right) |
| 21 | +# [3,9,11,8,20,15,7] |
| 22 | +# inorder -> (root-1(left) - left, root, right), root-2, (root-3(right) - left, root, right) |
| 23 | +# [11, 9, 8, 3, 15, 20, 7] |
| 24 | + |
| 25 | +# Ex4 [3,9,20,11,8] |
| 26 | +# preorder -> root-1, (root-2(left) - root, left, right), (root-3(right) - root) |
| 27 | +# [3,9,11,8,20] |
| 28 | +# inorder -> (root-1(left) - left, root, right), root-2, (root-3(right) - left(X), root) |
| 29 | +# [11, 9, 8, 3, 20] |
| 30 | + |
| 31 | +# ๋ฌธ์ ํ์ด : divide and conquer |
| 32 | +# preorder์ ์ฒซ๋ฒ์งธ ์์๋ฅผ ๊ฐ์ง๊ณ inorder split |
| 33 | +# split๋ left์ right์ ๊ฐ์์ ๋ง๊ฒ preorder์ ๋ ๋ฒ ์งธ ์์๋ถํฐ ์์๋๋ก ํ ๋น |
| 34 | +# ์) left ์์ ๊ฐ์ : 3 -> preorder[1:1+3], right ์์ ๊ฐ์ : 2 -> preorder[1+3:] |
| 35 | +# left, right ๊ฐ๊ฐ buildTree๋ก ๋ฃ๊ธฐ |
| 36 | + |
| 37 | +""" |
| 38 | +๋ณต์ก๋ : ์์ -> ์์ํ ์ด์ |
| 39 | +
|
| 40 | +์๊ฐ ๋ณต์ก๋ : O(n) -> ๋ถํ ํด์ ์ฒ๋ฆฌํ์ง๋ง, ๋ชจ๋ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๋ฏ๋ก |
| 41 | +๊ณต๊ฐ ๋ณต์ก๋ : O(n) -> ์
๋ ฅ ๋ฐฐ์ด๋งํผ์ ๊ธธ์ด์ ๊ฑฐ์ ๋์ผํ ๋ฐฐ์ด์ด ์์ฑ๋๋ฏ๋ก |
| 42 | +""" |
| 43 | +class Solution: |
| 44 | + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: |
| 45 | + if len(preorder) == 0: |
| 46 | + return None |
| 47 | + if len(preorder) == 1: |
| 48 | + return TreeNode(preorder[0]) |
| 49 | + root = TreeNode(preorder[0]) |
| 50 | + |
| 51 | + split_idx = inorder.index(preorder[0]) |
| 52 | + left_inorder = inorder[:split_idx] |
| 53 | + right_inorder = inorder[split_idx+1:] |
| 54 | + left_preorder = preorder[1:len(left_inorder)+1] |
| 55 | + right_preorder = preorder[len(left_inorder)+1:] |
| 56 | + root.left = self.buildTree(left_preorder, left_inorder) |
| 57 | + root.right = self.buildTree(right_preorder, right_inorder) |
| 58 | + return root |
| 59 | + |
0 commit comments