501.二叉搜索树中的众数
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
\
2
/
2
返回[2]
//中序遍历,比较当前节点值和上一节点值是否相同,相同则count+1;否则更新当前节点;
// count=maxCount 则将当前节点加入list,若大于,则清空list再更新
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
int count=0;
int maxCount=0;
int current=0;
public int[] findMode(TreeNode root) {
inOrder(root);
int res[] = new int[list.size()];
for(int i=0;i<list.size();i++){
res [i]=list.get(i);
}
return res;
}
public void inOrder(TreeNode root){
if(root==null)
return;
inOrder(root.left);
int rootVal = root.val;
if(rootVal==current){
count++;
}else{
current=rootVal;
count=1;
}
if(count==maxCount){
list.add(rootVal);
}else if(count>maxCount){
list.clear();
maxCount=count;
list.add(rootVal);
}
inOrder(root.right);
}
}

浙公网安备 33010602011771号