更新 0501.二叉搜索树中的众数 go版(原先的写法有问题,过不了leetcode)

原先的写法有问题,过不了leetcode,更新正确的解法
This commit is contained in:
NevS
2021-06-29 22:41:40 +08:00
committed by GitHub
parent 011b0cc6fd
commit f85d1c1a37

View File

@ -474,7 +474,7 @@ func traversal(root *TreeNode,history map[int]int){
} }
``` ```
计数法BSL此代码在执行代码里能执行但提交后报错不知为何思路是对的 计数法,不使用额外空间,利用二叉树性质,中序遍历
```go ```go
/** /**
@ -485,41 +485,35 @@ func traversal(root *TreeNode,history map[int]int){
* Right *TreeNode * Right *TreeNode
* } * }
*/ */
var count,maxCount int //统计计数 func findMode(root *TreeNode) []int {
func findMode(root *TreeNode) []int { res := make([]int, 0)
var result []int count := 1
var pre *TreeNode //前指针 max := 1
if root.Left==nil&&root.Right==nil{ var prev *TreeNode
result=append(result,root.Val) var travel func(node *TreeNode)
return result travel = func(node *TreeNode) {
} if node == nil {
traversal(root,&result,pre) return
return result }
} travel(node.Left)
func traversal(root *TreeNode,result *[]int,pre *TreeNode){//遍历统计 if prev != nil && prev.Val == node.Val {
//如果BSL中序遍历相邻的两个节点值相同则统计频率如果不相同依据BSL中序遍历排好序的性质重新计数 count++
if pre==nil{ } else {
count=1 count = 1
}else if pre.Val==root.Val{ }
count++ if count >= max {
}else { if count > max && len(res) > 0 {
count=1 res = []int{node.Val}
} } else {
//如果统计的频率等于最大频率,则加入结果集;如果统计的频率大于最大频率,更新最大频率且重新将结果加入新的结果集中 res = append(res, node.Val)
if count==maxCount{ }
*result=append(*result,root.Val) max = count
}else if count>maxCount{ }
maxCount=count//重新赋值maxCount prev = node
*result=[]int{}//清空result中的内容 travel(node.Right)
*result=append(*result,root.Val)
}
pre=root//保存上一个的节点
if root.Left!=nil{
traversal(root.Left,result,pre)
}
if root.Right!=nil{
traversal(root.Right,result,pre)
} }
travel(root)
return res
} }
``` ```