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

Commit 379e959

Browse files
committed
增加 222 题
1 parent a7a6e0b commit 379e959

File tree

2 files changed

+103
-0
lines changed

2 files changed

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

0 commit comments

Comments
 (0)