Skip to content

Commit 9264bff

Browse files
author
easyone
committed
Feat: Add solution of construct-binary-tree-from-preorder-and-inorder-traversal
1 parent f83acab commit 9264bff

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 풀이
2+
// preorder[0]이 제일 꼭대기
3+
// preorder 배열의 root index, inorder 배열의 시작, inorder 배열의 끝
4+
// 위의 세가지를 parameter로 받는 재귀함수를 만들어서
5+
// 왼쪽 서브트리, 오른쪽 서브트리를 순회
6+
7+
// TC
8+
// map 만들기 O(n) + 재귀함수는 각 노드를 딱 한번씩만 방문하므로 O(n) = O(n)
9+
10+
// SC
11+
// map O(n) + 재귀함수 최악의 경우 한쪽으로만 노드가 이어지는 경우 O(n) = O(n)
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* type TreeNode struct {
16+
* Val int
17+
* Left *TreeNode
18+
* Right *TreeNode
19+
* }
20+
*/
21+
22+
func buildTree(preorder []int, inorder []int) *TreeNode {
23+
inorderMap := make(map[int]int)
24+
for i, n := range inorder {
25+
inorderMap[n] = i
26+
}
27+
28+
var recursive func(rootIndex, inStart, inEnd int) *TreeNode
29+
recursive = func(rootIndex, inStart, inEnd int) *TreeNode {
30+
if rootIndex >= len(preorder) || inStart > inEnd {
31+
return nil
32+
}
33+
rootVal := preorder[rootIndex]
34+
rootInorderIndex := inorderMap[rootVal]
35+
36+
result := &TreeNode{
37+
Val: rootVal,
38+
}
39+
40+
leftSize := rootInorderIndex - inStart
41+
42+
result.Left = recursive(rootIndex+1, inStart, rootInorderIndex-1)
43+
result.Right = recursive(rootIndex+1+leftSize, rootInorderIndex+1, inEnd)
44+
45+
return result
46+
}
47+
48+
return recursive(0, 0, len(inorder)-1)
49+
}
50+

0 commit comments

Comments
 (0)