-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path501_find_mode_test.go
64 lines (57 loc) · 1.14 KB
/
501_find_mode_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package _5_binary_tree
import (
"github.com/smartystreets/goconvey/convey"
"testing"
)
// 二叉搜索树中的众数 https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
func TestFindMode(t *testing.T) {
convey.Convey("二叉搜索树中的众数", t, func() {
testCase := []struct {
input *TreeNode
target []int
}{
{
Ints2TreeNode([]int{1, NULL, 2, 2}),
[]int{2},
},
{
Ints2TreeNode([]int{0}),
[]int{0},
},
}
for _, tst := range testCase {
rsp := findMode(tst.input)
convey.So(rsp, convey.ShouldEqual, tst.target)
}
})
}
func findMode(root *TreeNode) (answer []int) {
// -105 <= Node.val <= 105
var base, count, maxCount int
update := func(x int) {
// 首先更新 base 和 count
if x == base {
count++
} else {
base, count = x, 1
}
// 然后更新 maxCount
if count == maxCount {
answer = append(answer, base)
} else if count > maxCount {
maxCount = count
answer = []int{base}
}
}
var dfs func(*TreeNode)
dfs = func(node *TreeNode) {
if node == nil {
return
}
dfs(node.Left)
update(node.Val)
dfs(node.Right)
}
dfs(root)
return
}