欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > 力扣【501. 二叉搜索树中的众数】Java题解

力扣【501. 二叉搜索树中的众数】Java题解

2025/6/22 10:47:30 来源:https://blog.csdn.net/weixin_61026052/article/details/145384312  浏览:    关键词:力扣【501. 二叉搜索树中的众数】Java题解

题目要求不使用额外空间。

思路:

可以两次遍历,第一次找到众数的节点个数,第二次找出众数数组。
但我们可以把这两次遍历改为一次遍历,就是找众数的节点个数时同时去更新众数数组,当maxCount等于count时,追加当前节点的值到众数数组中;当maxCount大于count时,将结果数组清空后加入当前节点。

代码:

class Solution {int maxCount=0; //目前众数节点的个数int count;  //目前节点的个数ArrayList<Integer> list=new ArrayList<>(); //存放结果TreeNode preNode; //前一个节点,一开始没有public int[] findMode(TreeNode root) {find(root);//将集合转换为数组int[] res = new int[list.size()];for(int i=0;i<list.size();i++){res[i] = list.get(i);}return res;}public void find(TreeNode root) {//非空判断if(root == null) return;//遍历左子树find(root.left);//当前节点个数判断if(preNode!=null && preNode.val == root.val){count++;}else{count = 1;}//判断是否是众数,是则更新结果集合if(count == maxCount){list.add(root.val);}else if(count > maxCount){list = new ArrayList<>();list.add(root.val);maxCount = count;}preNode = root;//遍历右子树find(root.right);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词