题目描述:
标签:树
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
代码:
思路分析:
1、中序遍历,其中定义pre
2、递归结束条件,cur为空,返回
3、左递归searchBST(cur.left)
4、处理节点,如果pre为空,count=1,否则pre.val=cur.val则count++,否则count=1,并令pre=cur
5、判断count 和 maxcount ,如果等于,则添加进入list,如果大于,则更新maxcount,并清空list,再添加当前值
6、右递归searchBST(cur.right)
/**
* Definition for a binary tree node.
* public 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 {
List<Integer> list = new ArrayList<>();
int count;
int maxCount;
TreeNode pre;
public int[] findMode(TreeNode root) {
searchBST(root);
int[] mode = new int[list.size()];
for (int i = 0; i < list.size(); ++i) {
mode[i] = list.get(i);
}
return mode;
}
public void searchBST(TreeNode cur){
if(cur == null) return;
searchBST(cur.left);
if(pre == null){//第一个节点
count = 1;
}else if(pre.val == cur.val){//与前一个节点数值相同
count++;
}else{//与前一个节点数值不同
count = 1;
}
pre = cur;
if(count == maxCount){
list.add(cur.val);
}
if(count > maxCount){
maxCount = count;
list.clear();
list.add(cur.val);
}
searchBST(cur.right);
}
}