二叉搜索树中的众数
题目链接:力扣题目链接
难度:简单
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树
示例
输入:root = [1,null,2,2]
输出:[2]
思路
使用中序排序,遍历有序数组的元素出现频率,从头遍历,那么一定是相邻两个元素作比较,然后就把出现频率最高的元素输出就可以了。
二叉树的定义
//二叉树节点的定义。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(){}
TreeNode(int val){
this.val = val;
}
TreeNode(int val,TreeNode left,TreeNode right){
this.val = val;
this.left = left;
this.right = right;
}
}
递归代码
class Solution{
ArrayList<Integer> resList = new ArrayList<>();
int count = 0; // 统计频率
int maxCount = 0; // 最大频率
TreeNode pre = null; // 记录前一个节点
public int[] findMode(TreeNode root) {
findMode1(root);
int[] res = new int[resList.size()];
for(int i=0;i<resList.size();i++){
res[i] = resList.get(i);
}
return res;
}
private void findMode1(TreeNode root){
if(root == null) return;
findMode1(root.left); // 左
int rootVal = root.val;
//第一个节点 与前一个节点数值不同
if(pre == null || rootVal != pre.val){
count = 1;
// 与前一个节点数值相同
}else{
count++;
}
// 如果和最大值相同,放进result中
if(count == maxCount){
resList.add(rootVal);
// 如果计数大于最大值频率
}else if(count > maxCount){
// 很关键的一步,不要忘记清空result,之前result里的元素都失效了
resList.clear();
resList.add(rootVal);
// 更新最大频率
maxCount = count;
}
pre = root; // 更新上一个节点
findMode1(root.right); // 右
}
}
迭代代码
class Solution{
public int[] findMode(TreeNode root) {
ArrayList<Integer> resList = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
int count = 0;
int maxCount = 0;
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
if(cur != null){
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
if(pre == null || cur.val == pre.val){
count = 1;
}else{
count++;
}
if(count > maxCount){
resList.clear();
resList.add(cur.val);
maxCount = count;
}else if(count == maxCount){
resList.add(cur.val);
}
pre = cur;
cur = cur.right;
}
}
return resList.stream().mapToInt(Integer::intValue).toArray();
}
}