Leetcode 501.二叉搜索树中的众数 Find Mode in Binary Search Tree(Java)
##Tree##
二叉搜索树中的众数
二叉搜索树的中序遍历为有序序列,因此本题转换为在有序序列中寻找众数
max
记录已经遍历过的数中,出现的最大频次count
记录当前遍历的数出现的频次TreeNode pre
记录上一个遍历的结点,如果题目没有Integer.MAX_VALUE
,也可以将pre
声明为int
,并初始化为Integer.MAX_VALUE
LinkedList<Integer> tres
记录当前已经遍历过的数中,众数的结果集合
采用中序遍历二叉树
root.val == pre.val
,本次遍历结点的值与上一次遍历结点的值相等,该数频次count++
,否则出现了新的数,该数频次count
置为1
count == max
,新的众数出现,且该众数出现的频次和结果集中众数出现频次相同,将该众数加入结果集count > max
,新的众数出现,且该众数出现的频次大于结果集中众数的频次,将结果集清空,新的众数加入结果集,并且更新max
- 遍历结束后,
pre = root
时间复杂度: O(n)
class Solution {
int max = 1;
int count = 1;
TreeNode pre = null;
LinkedList<Integer> tres = new LinkedList<>();
public int[] findMode(TreeNode root) {
dfs(root);
int[] res = new int[tres.size()];
for (int i = 0; i < res.length; i ++) res[i] = tres.pollFirst();
return res;
}
public void dfs(TreeNode root) {
if (root == null) return;
dfs(root.left);
if (pre != null && root.val == pre.val) count++;
else count = 1;
if (count == max) tres.offerLast(root.val);
if (count > max) {
max = count;
tres.clear();
tres.offerLast(root.val);
}
pre = root;
dfs(root.right);
}
}