8000 更新 0501.二叉搜索树中的众数 go版(原先的写法有问题,过不了leetcode) · lee4code/leetcode-master@f85d1c1 · GitHub
[go: up one dir, main page]

Skip to content

Commit f85d1c1

Browse files
author
NevS
authored
更新 0501.二叉搜索树中的众数 go版(原先的写法有问题,过不了leetcode)
原先的写法有问题,过不了leetcode,更新正确的解法
1 parent 011b0cc commit f85d1c1

File tree

1 file changed

+29
-35
lines changed

1 file changed

+29
-35
lines changed

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

Lines changed: 29 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ func traversal(root *TreeNode,history map[int]int){
474474
}
475475
```
476476

477-
计数法BSL(此代码在执行代码里能执行,但提交后报错,不知为何,思路是对的)
477+
计数法,不使用额外空间,利用二叉树性质,中序遍历
478478

479479
```go
480480
/**
@@ -485,41 +485,35 @@ func traversal(root *TreeNode,history map[int]int){
485485
* Right *TreeNode
486486
* }
487487
*/
488-
var count,maxCount int //统计计数
489-
func findMode(root *TreeNode) []int {
490-
var result []int
491-
var pre *TreeNode //前指针
492-
if root.Left==nil&&root.Right==nil{
493-
result=append(result,root.Val)
494-
return result
495-
}
496-
traversal(root,&result,pre)
497-
return result
498-
}
499-
func traversal(root *TreeNode,result *[]int,pre *TreeNode){//遍历统计
500-
//如果BSL中序遍历相邻的两个节点值相同,则统计频率;如果不相同,依据BSL中序遍历排好序的性质,重新计数
501-
if pre==nil{
502-
count=1
503-
}else if pre.Val==root.Val{
504-
count++
505-
}else {
506-
count=1
507-
}
508-
//如果统计的频率等于最大频率,则加入结果集;如果统计的频率大于最大频率,更新最大频率且重新将结果加入新的结果集中
509-
if count==maxCount{
510-
*result=append(*result,root.Val)
511-
}else if count>maxCount{
512-
maxCount=count//重新赋值maxCount
513-
*result=[]int{}//清空result中的内容
514-
*result=append(*result,root.Val)
515-
}
516-
pre=root//保存上一个的节点
517-
if root.Left!=nil{
518-
traversal(root.Left,result,pre)
488+
func findMode(root *TreeNode) []int {
489+
res := make([]int, 0)
490+
count := 1
491+
max := 1
492+
var prev *TreeNode
493+
var travel func(node *TreeNode)
494+
travel = func(node *TreeNode) {
495+
if node == nil {
496+
return
497+
}
498+
travel(node.Left)
499+
if prev != nil && prev.Val == node.Val {
500+
count++
501+
} else {
502+
count = 1
503+
}
504+
if count >= max {
505+
if count > max && len(res) > 0 {
506+
res = []int{node.Val}
507+
} else {
508+
res = append(res, node.Val)
509+
}
510+
max = count
511+
}
512+
prev = node
513+
travel(node.Right)
519514
}
520-
if root.Right!=nil{
521-
traversal(root.Right,result,pre)
522-
}
515+
travel(root)
516+
return res
523517
}
524518
```
525519

0 commit comments

Comments
 (0)
0