当前位置: 代码迷 >> 综合 >> LeetCode-501. 二叉搜索树中的众数(Goland实现)
  详细解决方案

LeetCode-501. 二叉搜索树中的众数(Goland实现)

热度:47   发布时间:2024-02-22 03:32:37.0

LeetCode题号:501. 二叉搜索树中的众数

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
例如:
给定 BST [1,null,2,2],

   1
    \
     2
    /
   2
返回  [2]

注意:

是输出众数,如果没有重复值,那么就全部输出!

解题思路
1、前序遍历 统计出所有重复数 存入map
2、遍历map 输入众数

代码:

/*** Definition for a binary tree node.* type TreeNode struct {*     Val int*     Left *TreeNode*     Right *TreeNode* }*/
func findMode(root *TreeNode) []int {var m = make(map[int]int)m = traverses(m, root)var list1 []intvar list2 []intvar max int = 1for k, v := range m {if v > max {max = v//清空与max值相等而追加进list2中的元素,保证进list2中的重复值必须是最大或等大的list2 = []int{}}//追加与max相等的元素if v == max && v != 1 {list2 = append(list2, k)}//目的是考虑没有重复值的情况下,直接返回该list1即可list1 = append(list1, k)}//说明没有重复值,都是众数if max == 1 {return list1}return list2
}//先序遍历
func traverses(m map[int]int, node *TreeNode) map[int]int {if node == nil {return map[int]int{}}//累加重复值m[node.Val]++traverses(m, node.Left)traverses(m, node.Right)return m
}

 往期回顾:

【1】LeetCode-617. 合并二叉树(Goland实现)

【2】LeetCode-104. 二叉树的最大深度(Goland实现) 

【3】LeetCode-111. 二叉树的最小深度(Goland实现)


?如果文章对您有所帮助,就在文章的右上角或者文章的末尾点个赞吧!(づ ̄ 3 ̄)づ 

?如果喜欢大白兔分享的文章,就给大白兔点个关注吧!(?′?‵?)づ╭?~

?对文章有任何问题欢迎小伙伴们下方留言或者入群探讨【群号:708072830】

?鉴于个人经验有限,所有观点及技术研点,如有异议,请直接回复讨论(请勿发表攻击言论)