当前位置:网站首页>LeetCode 501 :二叉搜索樹中的眾數
LeetCode 501 :二叉搜索樹中的眾數
2022-06-10 23:35: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);
}
}
边栏推荐
- 期货开户有什么限制嘛?哪里最安全?
- 云图说|每个成功的业务系统都离不开APIG的保驾护航
- 宝塔计划任务Shell脚本定时删除某各目录下所有文件【记录】
- Kotlin语言现在怎么不火了?
- PwnTheBox,Web:hello
- Design language testing for functional testing: what tests are included in functional testing? What is the role of each
- SQL查询优化原理实例分析
- redis列表list常用命令大全
- Executor - Shutdown、ShutdownNow、awaitTermination 詳解與實戰
- PwnTheBox,Pwn:tutorial1
猜你喜欢
![[QPSK if] Verilog design of QPSK IF signal generation module based on FPGA](/img/7d/b021790f1fde266ff9aa360261d581.png)
[QPSK if] Verilog design of QPSK IF signal generation module based on FPGA

执行Oracle的SQL语句报错【ORA-00904: “CREATETIME“: 标识符无效】、【ORA-00913: 值过多】解决办法

云图说|每个成功的业务系统都离不开APIG的保驾护航

Chapter 6 - branch and bound method

iframe框架自适应大小/全屏显示网页框架的方法

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

leetcode 130. Surrounded regions (medium)

Solutions to the error reported by executing Oracle SQL statement [ora-00904: "createtime": invalid identifier] and [ora-00913: too many values]

Data and information resource sharing platform (IV)
![[论文分享] PATA: Fuzzing with Path Aware Taint Analysis](/img/f6/627344c5da588afcf70302ef29d134.png)
[论文分享] PATA: Fuzzing with Path Aware Taint Analysis
随机推荐
云图说|每个成功的业务系统都离不开APIG的保驾护航
Which securities company does qiniu's securities belong to? Is it safe?
集度夏一平:不是所有事都向李彦宏汇报,靠产品跟小米华为竞争
im即时通讯源码带教程/uniapp即时通讯源码,附安装教程
Exécuteur - shutdown, shutdown Now, awaittermination details and actual Fighting
MySQL related -0416
Why is the kotlin language not popular now?
一文带你了解J.U.C的FutureTask、Fork/Join框架和BlockingQueue
[flutter problem series Chapter 6] how to achieve the scrolling effect of list messages in flutter
期货开户有什么限制嘛?哪里最安全?
[paper sharing] pata: fuzzing with path aware Taint Analysis
SQL查询优化原理实例分析
Interview questions - written examination
可扩展到Max–MCU和MPU开发,使用相同的许可证
Dell r730 RAID5 installation server 2016 (disk larger than 2t)
Creation of thread pool
Redis list list common commands
LeetCode+ 21 - 25
字蛛(font-spider)教学——ttf/otf字体文件压缩
掌握高性能计算前,我们先了解一下它的历史