Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 9d43bca

Browse files
authored
Merge pull request #36 from mlkr/master
增加 222 题
2 parents a7a6e0b + 0ac731c commit 9d43bca

File tree

2 files changed

+109
-0
lines changed

2 files changed

+109
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package problem0222
2+
3+
type TreeNode struct {
4+
Val int
5+
Left *TreeNode
6+
Right *TreeNode
7+
}
8+
9+
func countNodes(root *TreeNode) int {
10+
if root == nil {
11+
return 0
12+
}
13+
14+
count := 0
15+
traverse(root, &count)
16+
return count
17+
}
18+
19+
func traverse(node *TreeNode, count *int) {
20+
if node == nil {
21+
return
22+
}
23+
24+
*count++
25+
26+
traverse(node.Left, count)
27+
traverse(node.Right, count)
28+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package problem0222
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
var questions = []struct {
10+
pre, in []int
11+
count int
12+
}{
13+
{
14+
[]int{},
15+
[]int{},
16+
0,
17+
},
18+
19+
{
20+
[]int{1, 2, 4, 5, 3, 6},
21+
[]int{4, 2, 5, 1, 6, 3},
22+
6,
23+
},
24+
}
25+
26+
func Test_countNodes(t *testing.T) {
27+
ast := assert.New(t)
28+
for _, q := range questions {
29+
root := prein2Tree(q.pre, q.in)
30+
ast.Equal(q.count, countNodes(root))
31+
}
32+
}
33+
34+
func Benchmark_countNodes(b *testing.B) {
35+
for i := 0; i < b.N; i++ {
36+
for _, q := range questions {
37+
root := prein2Tree(q.pre, q.in)
38+
countNodes(root)
39+
}
40+
}
41+
}
42+
43+
func prein2Tree(pre, in []int) *TreeNode {
44+
preLen := len(pre)
45+
inLen := len(in)
46+
if preLen != inLen {
47+
panic("pre in 数组长度不一致!")
48+
}
49+
50+
if preLen == 0 {
51+
return nil
52+
}
53+
54+
root := &TreeNode{
55+
Val: pre[0],
56+
}
57+
58+
if preLen == 1 {
59+
return root
60+
}
61+
62+
idx := indexOf(root.Val, in)
63+
if idx == -1 {
64+
panic("pre 或 in 数组有错!")
65+
}
66+
67+
root.Left = prein2Tree(pre[1:idx+1], in[:idx])
68+
root.Right = prein2Tree(pre[idx+1:], in[idx+1:])
69+
70+
return root
71+
}
72+
73+
func indexOf(val int, nums []int) int {
74+
for k, v := range nums {
75+
if v == val {
76+
return k
77+
}
78+
}
79+
80+
return -1
81+
}

0 commit comments

Comments
 (0)