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
| // @Title: 二叉搜索树中的众数 (Find Mode in Binary Search Tree)
// @Author: 15816537946@163.com
// @Date: 2019-11-30 11:22:07
// @Runtime: 32 ms
// @Memory: 6.6 MB
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
r:= make(map[int]int)
search(root,r)
fmt.Println(r)
max := -1
res := make([]int, 0)
for k,v := range r{
if max == v {
res = append(res, k)
}
if max < v {
max = v
fmt.Println("hit here")
res = []int{k}
}
}
return res
}
func search(root *TreeNode,rec map[int]int) {
if root == nil {
return
}
rec[root.Val]++
search(root.Left, rec)
search(root.Right,rec)
}
|