LeetCode | 0508. 出现次数最多的子树元素和【Python】

该博客介绍了如何解决力扣上的一个题目,即给定一棵二叉树,找出所有子树元素和中出现次数最多的那个。通过深度优先搜索(DFS)遍历树的节点,计算每个节点的子树元素和并存储到字典中,然后找出出现次数最多的子树元素和。代码使用Python实现,并给出了示例输入和输出。
摘要由CSDN通过智能技术生成

Problem

LeetCode

Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

  5
 /  \
2   -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

  5
 /  \
2   -5

return [2], since 2 happens twice, however -5 only occur once.

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

问题

力扣

给你一个二叉树的根结点,请你找出出现次数最多的子树元素和。一个结点的「子树元素和」定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。

你需要返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)。

示例 1:

输入:

  5
 /  \
2   -3

返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。

示例 2:
输入:

  5
 /  \
2   -5

返回 [2],只有 2 出现两次,-5 只出现 1 次。

提示: 假设任意子树元素和均可以用 32 位有符号整数表示。

思路

DFS

先思考每一个节点需要做的事:该节点值与左右子树的所有节点值相加。
同时,要记录次数。
再遍历子树元素和,取出次数最多的子树元素和。

Python3 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
        import collections
        res_dic = collections.defaultdict(int)
        # 计算子树元素和
        def dfs(node):
            # 递归边界
            if not node:
                return 0
            tmp_sum = dfs(node.left) + node.val + dfs(node.right)
            res_dic[tmp_sum] += 1
            return tmp_sum
        
        if not root:
            return []
        dfs(root)
        max_cnt = 0
        for cnt in res_dic.values():
            max_cnt = max(max_cnt, cnt)
        return [key for key, cnt in res_dic.items() if cnt == max_cnt]

GitHub 链接

Python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wonz

创作不易,一块就行。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值