Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
Example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
此题有个直观的解法,直接就二叉树遍历,记录每个值出现的次数,组成一个hash,然后遍历一遍这个hash,得知出现的最大次数,由于会出现多个最大的次数,因此,找到了最大的次数之后,还需要再遍历一遍,把出现这个最大次数的值都给找出来,也就是我们的解法一了。
这道题显然没有利用好BST的性质,至于怎么利用,还没有想好。TODO
// 解法一
func findMode(root *TreeNode) []int {
var mapping = make(map[int]int)
findModeCore(root, mapping)
var maxCount int
for _, v := range mapping {
if v > maxCount {
maxCount = v
}
}
var ret []int
for k, v := range mapping {
if v == maxCount {
ret = append(ret, k)
}
}
return ret
}
func findModeCore(root *TreeNode, mapping map[int]int) {
if root == nil {
return
}
mapping[root.Val]++
findModeCore(root.Left, mapping)
findModeCore(root.Right, mapping)
return
}