@@ -4,32 +4,28 @@ import (
4
4
"fmt"
5
5
"testing"
6
6
7
- "github.com/aQuaYi/LeetCode-in-Go/kit"
8
-
9
7
"github.com/stretchr/testify/assert"
10
8
)
11
9
12
10
// tcs is testcase slice
13
11
var tcs = []struct {
14
- pre , in []int
15
- ans int
12
+ nums []int
13
+ ans int
16
14
}{
17
15
16
+ // 用 0 表示 nil
18
17
{
19
- []int {5 , 2 , 4 , 1 , 3 , 1000 },
20
- []int {2 , 4 , 5 , 1 , 3 , 1000 },
21
- 1009 ,
18
+ []int {4 , 1 , 0 , 2 , 0 , 3 },
19
+ 7 ,
22
20
},
23
21
24
22
{
25
- []int {5 , 2 , 4 , 1 , 3 },
26
- []int {2 , 4 , 5 , 1 , 3 },
27
- 12 ,
23
+ []int {3 , 2 , 3 , 0 , 3 , 0 , 1 },
24
+ 7 ,
28
25
},
29
26
30
27
{
31
- []int {3 , 4 , 1 , 3 , 5 , 1 },
32
- []int {1 , 4 , 3 , 3 , 5 , 1 },
28
+ []int {3 , 4 , 5 , 1 , 3 , 0 , 1 },
33
29
9 ,
34
30
},
35
31
@@ -41,16 +37,57 @@ func Test_rob(t *testing.T) {
41
37
42
38
for _ , tc := range tcs {
43
39
fmt .Printf ("~~%v~~\n " , tc )
44
- root := kit .PreIn2Tree (tc .pre , tc .in )
40
+ root := & TreeNode {}
41
+ initTree (tc .nums , []* TreeNode {}, root )
45
42
ast .Equal (tc .ans , rob (root ), "输入:%v" , tc )
46
43
}
47
44
}
48
45
49
46
func Benchmark_rob (b * testing.B ) {
50
47
for i := 0 ; i < b .N ; i ++ {
51
48
for _ , tc := range tcs {
52
- root := kit .PreIn2Tree (tc .pre , tc .in )
49
+ root := & TreeNode {}
50
+ initTree (tc .nums , []* TreeNode {}, root )
53
51
rob (root )
54
52
}
55
53
}
56
54
}
55
+
56
+ // 创建二叉树
57
+ func initTree (nums []int , parents []* TreeNode , root * TreeNode ) {
58
+ if len (nums ) == 0 {
59
+ return
60
+ }
61
+
62
+ if len (parents ) == 0 {
63
+ if nums [0 ] != 0 {
64
+ root .Val = nums [0 ]
65
+ parents = append (parents , root )
66
+ initTree (nums [1 :], parents , root )
67
+ }
68
+
69
+ return
70
+ }
71
+
72
+ newParents := make ([]* TreeNode , 0 , len (parents )* 2 )
73
+ for _ , parent := range parents {
74
+
75
+ if nums [0 ] != 0 {
76
+ parent .Left = & TreeNode {Val : nums [0 ]}
77
+ newParents = append (newParents , parent .Left )
78
+ }
79
+
80
+ if len (nums ) == 1 {
81
+ return
82
+ }
83
+
84
+ if nums [1 ] != 0 {
85
+ parent .Right = & TreeNode {Val : nums [1 ]}
86
+ newParents = append (newParents , parent .Right )
87
+ }
88
+
89
+ nums = nums [2 :]
90
+ }
91
+
92
+ initTree (nums , newParents , root )
93
+ }
0 commit comments