黄哥Python: 501 题Find Mode in Binary Search Tree

220 阅读1分钟
原文链接: zhuanlan.zhihu.com

Leetcode 501 题,Find Mode in Binary Search Tree,解题思路。

1、 读题,求解bst 树中出现次数做多的node的值。

2、二叉树的题目,一般都是dfs、bfs 算法去解决。

3、该题用字典去保存dfs 遍历node 得到的值,以node的值为字典的key,出现的次数为字典的值。

4、化解为求字典中,值最大的key值的问题。

Python代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# 黄哥Python培训 黄哥所写
class Solution:
    def findMode(self, root: TreeNode) -> List[int]:
        if root is None:
            return []
        if root.left is None and root.right is None:
            return [root.val]
        d = {}
        def dfs(root):
            if root is None:
                return []
            if root.val not in d:
                d[root.val] = 1
            else:
                d[root.val] += 1
            dfs(root.left)
            dfs(root.right)
        dfs(root)
        maxval = max(d.values())
        return [key for key in d if d[key] == maxval]

Go 语言代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
// 黄哥Python培训 黄哥所写
func findMode(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }
    var res []int
    d := map[int]int{}
    dfs(root, d)
    // fmt.Println(d)
    max := d[root.Val]
    for _, val := range d {
        if val > max {
            max = val
        }
    }
    for key,val := range d {
        if val == max {
            res = append(res, key)
        }
    }
    return res
    
}

func dfs(root *TreeNode, d map[int]int) {
    if root == nil {
        return
    }
    value := root.Val
    if _, ok := d[value]; ok {
        d[value]++
    }else{
        d[value] = 1
    }
    dfs(root.Left, d)
    dfs(root.Right, d)
}
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标