Skip to content

Commit 471459b

Browse files
aQuaaQua
aQua
authored and
aQua
committed
105 accepted. 52ms. The Fastest is 38ms.
1 parent 22499e6 commit 471459b

File tree

3 files changed

+44
-9
lines changed

3 files changed

+44
-9
lines changed

Algorithms/0105.construct-binary-tree-from-preorder-and-inorder-traversal/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
## 题目
44
Given preorder and inorder traversal of a tree, construct the binary tree.
55

6-
Note:
6+
**Note:**
77
You may assume that duplicates do not exist in the tree.
88

99
## 解题思路
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,37 @@
11
package Problem0105
2+
import (
3+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
4+
)
5+
type TreeNode = kit.TreeNode
26

3-
func buildTree(preorder []int, inorder []int) *TreeNode {
7+
func buildTree(pre, in []int) *TreeNode {
48

9+
if len(in) == 0 {
10+
return nil
11+
}
12+
13+
res := &TreeNode{
14+
Val: pre[0],
15+
}
16+
17+
if len(in) == 1 {
18+
return res
19+
}
20+
21+
idx := indexOf(res.Val, in)
22+
23+
res.Left = buildTree(pre[1:idx+1], in[:idx])
24+
res.Right = buildTree(pre[idx+1:], in[idx+1:])
25+
26+
return res
27+
}
28+
29+
func indexOf(val int, nums []int) int {
30+
for i, v := range nums {
31+
if v == val {
32+
return i
33+
}
34+
}
35+
36+
return 0
537
}
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package Problem0105
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
68

79
"github.com/stretchr/testify/assert"
810
)
@@ -15,12 +17,12 @@ type question struct {
1517
// para 是参数
1618
type para struct {
1719
preorder []int
18-
inorder []int
20+
inorder []int
1921
}
2022

2123
// ans 是答案
2224
type ans struct {
23-
one *TreeNode
25+
postorder []int
2426
}
2527

2628
func Test_Problem0105(t *testing.T) {
@@ -30,20 +32,21 @@ func Test_Problem0105(t *testing.T) {
3032

3133
question{
3234
para{
33-
,
35+
[]int{1, 2, 4, 5, 3, 6, 7},
36+
[]int{4, 2, 5, 1, 6, 3, 7},
3437
},
3538
ans{
36-
,
39+
[]int{4, 5, 2, 6, 7, 3, 1},
3740
},
3841
},
39-
42+
4043
// 如需多个测试,可以复制上方元素。
4144
}
4245

4346
for _, q := range qs {
4447
a, p := q.ans, q.para
4548
fmt.Printf("~~%v~~\n", p)
4649

47-
ast.Equal(a.one, buildTree(p. ), "输入:%v", p)
50+
ast.Equal(a.postorder, kit.Tree2Postorder(buildTree(p.preorder, p.inorder)), "输入:%v", p)
4851
}
4952
}

0 commit comments

Comments
 (0)