当前位置: 首页> 文旅> 艺术 > 代码随想录——二叉搜索树中的众数(Leetcode501)

代码随想录——二叉搜索树中的众数(Leetcode501)

时间:2025/7/10 0:31:57来源:https://blog.csdn.net/qq_46574748/article/details/139401642 浏览次数:0次

题目链接
在这里插入图片描述

中序遍历

/*** 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 max = 0;int count = 0;TreeNode pre = null;ArrayList<Integer> array = new ArrayList<Integer>();public int[] findMode(TreeNode root) {traversal(root);// 把ArrayList转为int[]int[] result = new int[array.size()];for (int i = 0; i < array.size(); i++) {result[i] = array.get(i);}return result;}// 中序遍历public void traversal(TreeNode root){if(root == null){return ;}// 左traversal(root.left);// 中if(pre == null){count = 1;}else if(pre.val == root.val){count++;}else{count = 1;}pre = root;if(count == max){array.add(root.val);}if(count > max){max = count;// ArrayList中清空数组函数clear()array.clear();array.add(root.val);}// 右traversal(root.right);}
}

由于二叉搜索树中序遍历是升序的特性,所以当看到题目中是二叉搜索树时,首先可以想用中序遍历来解决。

关键字:代码随想录——二叉搜索树中的众数(Leetcode501)

版权声明:

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

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

责任编辑: