java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846 |
---|
解题思路 |
---|
- 二叉搜索树,是有序的,而其中序遍历正好是升序序列
- 有了中序遍历序列,就可以通过依次遍历,统计每一个数字的出现次数
- 每次记录最多出现次数的数,作为众数保存。
- 如果连续多个众数出现次数相同,直接添加到答案中
- 如果出现一个新的众数,比已经保存的出现次数多,那么清空答案,添加这个新的。
代码 |
---|
/**
* 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 {
int base = -1;//当前统计个数的值
int count = 0;//当前值的个数
int countMax = 0;//当前出现次数最多的次数
List<Integer> answer = new ArrayList<Integer>();//保存答案
public int[] findMode(TreeNode root) {//程序入口
dfs(root);//进入中序遍历,获取answer链表
//将链表转换为数组返回
int[] mode = new int[answer.size()];
for(int i = 0; i < answer.size(); i++) mode[i] = answer.get(i);
return mode;
}
//中序遍历
public void dfs(TreeNode root) {
if(root == null) return;
dfs(root.left);
//中,变为统计众数操作
update(root.val);
dfs(root.right);
}
//统计
private void update(int val){
if(val == base) count++;//如果当前值,是正在统计个数的值,就次数+1
else{//如果不是,就重新统计
count = 1;
base = val;
}
//比较当前统计次数,和最大次数
if(count == countMax) answer.add(base);//如果和上一个众数的统计结果相同,也加入到链表
else if(count > countMax) {//如果比上一个众数出现次数更大
answer.clear();//当前链表中的众数就不要了,我们只要最大的
countMax = count;//然后最多出现次数更新
answer.add(base);//将此众数添加到链表
}
}
}