File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
3
+ 두 개의 정수 배열 preorder와 inoder가 주어졌을 때 이진 트리를 구성하고 반환하시오.
4
+ preorder = 전위 순회 : 루트 -> 왼쪽 서브트리 -> 오른쪽 서브트리
5
+ inorder = 중위 순회 : 왼쪽 서브트리 -> 루트 -> 오른쪽 서브트리
6
+
7
+ TC: O(n), n: 노드 수
8
+ SC: O(n)
9
+ """
10
+
11
+ from typing import Optional , List
12
+
13
+ # Definition for a binary tree node.
14
+ class TreeNode :
15
+ def __init__ (self , val = 0 , left = None , right = None ):
16
+ self .val = val
17
+ self .left = left
18
+ self .right = right
19
+
20
+ class Solution :
21
+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
22
+ if not preorder or not inorder :
23
+ return None
24
+
25
+ # 1. preorder의 첫 값이 root
26
+ root_val = preorder [0 ]
27
+ root = TreeNode (root_val )
28
+
29
+ # 2. inorder에서 root 위치 찾기
30
+ root_index = inorder .index (root_val )
31
+
32
+ # 3. 왼쪽, 오른쪽 나눠서 재귀적으로 연결
33
+ root .left = self .buildTree (preorder [1 :root_index + 1 ], inorder [:root_index ])
34
+ root .right = self .buildTree (preorder [root_index + 1 :], inorder [root_index + 1 :])
35
+
36
+ return root
You can’t perform that action at this time.
0 commit comments