LC501. 二叉搜索树中的众数
题目
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
解题思路
其实这题解题思路很简单,就是遍历二叉树,将遍历到的值在哈希表中计数,最后输出众数即可。
代码
Python
1 | class Solution: |
C++
1 | class Solution { |
Go
func findMode(root *TreeNode) []int {
hash := make(map[int]int)
dfs(root, hash)
max := math.MinInt64
ans := make([]int, 0, 0)
for x, c := range hash {
if c > max {
ans = make([]int, 0, 0)
ans = append(ans, x)
max = c
} else if c == max {
ans = append(ans, x)
}
}
return ans
}
func dfs(node *TreeNode, hash map[int]int){
if (node == nil) {return}
hash[node.Val]++
dfs(node.Left, hash)
dfs(node.Right, hash)
}
评论
