本题的解法学习于代码随想录
思路:二叉搜索树相关的算法题要使用到二叉搜索树的特性,本题的难点是如何将出现相同次数的众数保存起来,以及count条件的转换。
JAVA版本:
解法一:使用递归的方法来完成
class Solution {
//先定义需要的变量
int count =0; //次数
int maxCount =0; //最大值
TreeNode pre = null;//前一个结点
ArrayList<Integer> resList = new ArrayList<>();//定义存储众数的数组
public int[] findMode(TreeNode root) {
checkNum(root); //定义递归函数
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
}
public void checkNum(TreeNode root){
if(root ==null) {
return;
}
//使用二叉排序树的特性来进行中序遍历
checkNum(root.left);
int rootValue = root.val;
//**注意查找到相关众数的条件 */
if(pre ==null || rootValue != pre.val){
//root结点的值跟pre结点的值来比较,利用二叉排序树的特性
count =1;
}else{
count++;
}
//更新最新的结果
if(count > maxCount){
resList.clear(); //**清空数组很重要 */
resList.add(rootValue);
maxCount = count;
}else if (count == maxCount){ //解决出现了多个相同次数众数的问题
resList.add(rootValue);
}
pre = root;
checkNum(root.right);
}
}
解法二:使用迭代的方式,二叉树的中序遍历
class Solution {
public int[] findMode(TreeNode root) {
TreeNode pre = null;
Stack<TreeNode> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
int maxCount = 0;
int count = 0;
TreeNode cur = root;
while(cur !=null ||!stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
cur =cur.left;
}else {
cur = stack.pop();
// 计数
if (pre == null || cur.val != pre.val) {
count = 1;
}else {
count++;
}
// 更新结果
if (count > maxCount) {
maxCount = count;
result.clear();
result.add(cur.val);
}else if (count == maxCount) {
result.add(cur.val);
}
pre = cur;
cur = cur.right;
}
}
int[] res = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
res[i] = result.get(i);
}
return res;
}
}
总结:本题的难点是终止条件的判断,以及最大的众数的切换的条件,迭代的思路与上一题中大致相同,只需要注意条件的改变。