Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit178cf44

Browse files
author
xeniaxie(xl)
committed
0501二叉搜索树中的众数JavaScript版本
1 parenta72bbac commit178cf44

File tree

1 file changed

+73
-1
lines changed

1 file changed

+73
-1
lines changed

‎problems/0501.二叉搜索树中的众数.md

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,79 @@ func traversal(root *TreeNode,result *[]int,pre *TreeNode){//遍历统计
522522
}
523523
}
524524
```
525-
525+
JavaScript版本:
526+
使用额外空间map的方法:
527+
```javascript
528+
varfindMode=function(root) {
529+
// 使用递归中序遍历
530+
let map=newMap();
531+
// 1. 确定递归函数以及函数参数
532+
consttraverTree=function(root) {
533+
// 2. 确定递归终止条件
534+
if(root===null) {
535+
return ;
536+
}
537+
traverTree(root.left);
538+
// 3. 单层递归逻辑
539+
map.set(root.val,map.has(root.val)?map.get(root.val)+1:1);
540+
traverTree(root.right);
541+
}
542+
traverTree(root);
543+
//上面把数据都存储到map
544+
//下面开始寻找map里面的
545+
// 定义一个最大出现次数的初始值为root.val的出现次数
546+
let maxCount=map.get(root.val);
547+
// 定义一个存放结果的数组res
548+
let res= [];
549+
for(let [key,value]of map) {
550+
// 如果当前值等于最大出现次数就直接在res增加该值
551+
if(value=== maxCount) {
552+
res.push(key);
553+
}
554+
// 如果value的值大于原本的maxCount就清空res的所有值,因为找到了更大的
555+
if(value>maxCount) {
556+
res= [];
557+
maxCount= value;
558+
res.push(key);
559+
}
560+
}
561+
return res;
562+
};
563+
```
564+
不使用额外空间,利用二叉树性质,中序遍历(有序):
565+
```javascript
566+
varfindMode=function(root) {
567+
// 不使用额外空间,使用中序遍历,设置出现最大次数初始值为1
568+
let count=0,maxCount=1;
569+
let pre= root,res= [];
570+
// 1.确定递归函数及函数参数
571+
consttravelTree=function(cur) {
572+
// 2. 确定递归终止条件
573+
if(cur===null) {
574+
return ;
575+
}
576+
travelTree(cur.left);
577+
// 3. 单层递归逻辑
578+
if(pre.val===cur.val) {
579+
count++;
580+
}else {
581+
count=1;
582+
}
583+
pre= cur;
584+
if(count=== maxCount) {
585+
res.push(cur.val);
586+
}
587+
if(count> maxCount) {
588+
res= [];
589+
maxCount= count;
590+
res.push(cur.val);
591+
}
592+
travelTree(cur.right);
593+
}
594+
travelTree(root);
595+
return res;
596+
};
597+
```
526598

527599

528600
-----------------------

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp