当前位置:网站首页>LeetCode 501 :二叉搜索树中的众数
LeetCode 501 :二叉搜索树中的众数
2022-06-10 22:21:00 【斯沃福德】
题目:

思路:
使用pre节点和root节点进行比较
用count来记录节点值重复的次数
①先确定count值才能确定是否添加root值
若pre为null,或者pre和root值不等时 则开始记数;如果pre和root等则count++累加
②用count和max比较,如果count比max大,则之前list存的都无效,清除list
若count=max,即有新的众数出现,添加至list
若count<max,忽略
class Solution {
int count=0;
int max=Integer.MIN_VALUE;
TreeNode pre=null;
ArrayList<Integer> list;
public int[] findMode(TreeNode root) {
list=new ArrayList<>();
check(root);
int n=list.size();
int[]r =new int[n];
for(int i=0;i<n;i++){
r[i]=list.get(i);
}
return r;
}
void check(TreeNode root){
if(root==null){
return;
}
check(root.left);
//中序遍历
//开始记数,重新记数
if(pre==null || pre.val!=root.val){
count=1;
}else if(root.val==pre.val){
count++;
}
//存入结果
if(count>max){
// 若有重复的则只存count最高那个节点的值!
list.clear();
list.add(root.val);
max=count;
}else if(count==max){
list.add(root.val);
}
//count<max则不存
pre=root;
check(root.right);
}
}
边栏推荐
- Kotlin语言现在怎么不火了?
- 在Oracle表中如何进行关键词搜索
- 第六章——分枝限界法
- Electronic Society C language level 1 7. Draw rectangle
- 中银证券股票开户安全吗?是正规的吗?
- Data and information resource sharing platform (VIII)
- Ma8601 pin √ pin replaces Tang Ming fe1.1s without changing the circuit board | perfectly replaces fe1.1s scheme
- 中金财富证券证券股票开户安全吗?靠谱吗?
- 30 frequently asked questions of 2022 latest software test interview questions [continuous update ~]
- Laravel8 enables alicloud file upload
猜你喜欢

软件测试入门之软件测试的概念与过程(精辟内容)

28岁自学编程会不会太晚了?靠谱吗?

Wireshark抓取rtp负载ts流介绍(UDP组播)

Introduction to Wireshark capturing RTP load TS stream (UDP multicast)

样板小作坊

关于idea中src下 无法new一个package

可扩展到Max–MCU和MPU开发,使用相同的许可证

Development and implementation of AI intelligent video analysis easycvr platform device channel batch deletion function

Data and information resource sharing platform (VIII)

Exécuteur - shutdown, shutdown Now, awaittermination details and actual Fighting
随机推荐
300 questions on behalf of the first lecture on determinant
在Oracle表中如何进行关键词搜索
Expandable to Max – MCU and MPU development, using the same license
Ride the storm and explore the secret behind the open source of flyfish, a data visualization development platform!
Introduction to Wireshark capturing RTP load TS stream (UDP multicast)
Halcon combined with C # to detect surface defects -- affine transformation (II)
Project training 12 - parsing SQL statements for creating tables
【Flutter 问题系列第 6 篇】如何在 Flutter 中实现列表消息的滚动效果
司空见惯 - 大哲学家康德的作息时间表
Ribbon load balancing policy
leetcode 130. Surrounded Regions 被围绕的区域(中等)
数据与信息资源共享平台(六)
上海证券开户是安全的吗?
How to search keywords in Oracle tables
PwnTheBox,Pwn:tutorial1
Is it safe to open a BOC securities account? Is the risk high?
Clustered and non clustered indexes
28岁自学编程会不会太晚了?靠谱吗?
2022最新软件测试面试题常问的30道【持续更新~】
Executor - Shutdown、ShutdownNow、awaitTermination 詳解與實戰