Skip to content

Commit 61ddf7a

Browse files
aQuaaQua
aQua
authored and
aQua
committed
106 finish
1 parent cedd8e2 commit 61ddf7a

File tree

3 files changed

+51
-10
lines changed

3 files changed

+51
-10
lines changed

Algorithms/0106.construct-binary-tree-from-inorder-and-postorder-traversal/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
## 题目
44
Given inorder and postorder 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,39 @@
11
package Problem0106
22

3-
func buildTree(inorder []int, postorder []int) *TreeNode {
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
5+
)
46

7+
type TreeNode = kit.TreeNode
8+
9+
func buildTree(in []int, post []int) *TreeNode {
10+
if len(in) == 0 {
11+
return nil
12+
}
13+
14+
res := &TreeNode{
15+
Val: post[len(post)-1],
16+
}
17+
18+
if len(in) == 1 {
19+
return res
20+
}
21+
22+
idx := indexOf(res.Val, in)
23+
24+
res.Left = buildTree(in[:idx], post[:idx])
25+
res.Right = buildTree(in[idx+1:], post[idx:len(post)-1])
26+
27+
return res
28+
}
29+
30+
31+
func indexOf(val int, nums []int) int {
32+
for i, v := range nums {
33+
if v == val {
34+
return i
35+
}
36+
}
37+
38+
return 0
539
}
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package Problem0106
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
)
@@ -14,13 +16,13 @@ type question struct {
1416

1517
// para 是参数
1618
type para struct {
17-
inorder []int
18-
postorder []int
19+
inorder []int
20+
postorder []int
1921
}
2022

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

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

3133
question{
3234
para{
33-
,
35+
[]int{4, 2, 5, 1, 6, 3, 7},
36+
[]int{4, 5, 2, 6, 7, 3, 1},
3437
},
3538
ans{
36-
,
39+
[]int{1, 2, 4, 5, 3, 6, 7},
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.pre, kit.Tree2Preorder(buildTree(p.inorder, p.postorder)), "输入:%v", p)
4851
}
52+
53+
ast.Nil(buildTree([]int{}, []int{}))
54+
55+
ast.Equal(0, indexOf(3, []int{0, 1, 2}))
4956
}

0 commit comments

Comments
 (0)