当前位置:网站首页>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);
}
}
边栏推荐
- [论文分享] PATA: Fuzzing with Path Aware Taint Analysis
- Pulling method of common webcam
- Reptiles learn knowledge
- About string format(String format, Object... args)
- 字蛛(font-spider)教学——ttf/otf字体文件压缩
- 一 组工人合作完成某一部件的装配工序所需的时间(单位:分钟)分别如下:
- Which securities company does qiniu's securities belong to? Is it safe?
- OpenVP*整合ldap认证
- Wireshark抓取rtp负载ts流介绍(UDP组播)
- Executor - Shutdown、ShutdownNow、awaitTermination 详解与实战
猜你喜欢

leetcode 130. Surrounded Regions 被围绕的区域(中等)

Data and information resource sharing platform (V)

Before we learn about high-performance computing, let's take a look at its history

LeetCode+ 21 - 25

乘风破浪,探索数据可视化开发平台 FlyFish 开源背后的秘密!
![[gmm+kde] target tracking simulation based on GMM and KDE kernel estimation of MATLAB](/img/44/f2b6ddf49b6d985129f57195e858eb.png)
[gmm+kde] target tracking simulation based on GMM and KDE kernel estimation of MATLAB

The time (in minutes) required for a group of workers to cooperate to complete the assembly process of a part are as follows:

Laravel8 enables alicloud file upload

字蛛(font-spider)教学——ttf/otf字体文件压缩

LeetCode+ 21 - 25
随机推荐
28岁自学编程会不会太晚了?靠谱吗?
R 语言绘制二维正态分布的密度曲面图;
Executor - Shutdown、ShutdownNow、awaitTermination 详解与实战
Commonplace - the timetable of the great philosopher Kant
Six procurement challenges perplexing Enterprises
关于嵌入式音频开发需要注意的两个方面
34. find the first and last positions of elements in the sorted array - binary search, double pointer
Is qiniu's securities account true? Is it safe?
Is it safe for CICC Fortune Securities to open an account? Is it reliable?
项目实训12——解析建表的SQL语句
可扩展到Max–MCU和MPU开发,使用相同的许可证
OpenVP*整合ldap認證
PwnTheBox,Pwn:tutorial1
PwnTheBox,Web:hello
Expandable to Max – MCU and MPU development, using the same license
OpenVP*整合ldap认证
Openvp * consolider l'authentification LDAP
Is it safe for BOC securities to open an account? Is it formal?
上海证券开户是安全的吗?
MySQL composite index is not used by hits