@@ -474,7 +474,7 @@ func traversal(root *TreeNode,history map[int]int){
474
474
}
475
475
```
476
476
477
- 计数法BSL(此代码在执行代码里能执行,但提交后报错,不知为何,思路是对的)
477
+ 计数法,不使用额外空间,利用二叉树性质,中序遍历
478
478
479
479
``` go
480
480
/* *
@@ -485,41 +485,35 @@ func traversal(root *TreeNode,history map[int]int){
485
485
* Right *TreeNode
486
486
* }
487
487
*/
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 )
519
514
}
520
- if root.Right !=nil {
521
- traversal (root.Right ,result,pre)
522
- }
515
+ travel (root)
516
+ return res
523
517
}
524
518
```
525
519
0 commit comments