LeetCode-501. Mode in Binary Search Tree (implemented in Golang)

LeetCode question number: 501. Mode in the binary search tree

Given a binary search tree (BST) with the same value, find all modes (the most frequent element) in the BST.
For example:
given BST [1,null,2,2],

   1
    \
     2
    /
   2
Back [2]

note:

Is the output mode, if there is no duplicate value, then all output!

Problem-solving ideas
1. Pre-order traversal and count all the repeated numbers and store them in the map
2. Traverse the map and enter the mode

Code:

/**
 * 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 []int
    var list2 []int
    var max int = 1
    for 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
}

 Past review:

[1] LeetCode-617. Merging Binary Trees (implemented by Goland)

[2] LeetCode-104. Maximum depth of binary tree (implemented by Goland) 

[3] LeetCode-111. The minimum depth of a binary tree (implemented by Goland)


❤If the article is helpful to you, please click like at the top right corner of the article or at the end of the article! (づ ̄ 3 ̄)づ 

❤If you like the articles shared by the white rabbit, please pay attention to the white rabbit! (๑′ᴗ‵๑)づ╭❤~

❤If you have any questions about the article, please leave a message below or join the group to discuss [group number: 708072830]

❤In view of the limited personal experience, all opinions and technical research points, if you have any objections, please reply directly to the discussion (do not make offensive remarks)

Guess you like

Origin blog.csdn.net/weixin_43970743/article/details/108773621