当前位置:网站首页>【二叉树-中等】508. 出现次数最多的子树元素和
【二叉树-中等】508. 出现次数最多的子树元素和
2022-08-10 01:52:00 【菜菜2022】
【题目】
给你一个二叉树的根结点 root ,请返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)
一个结点的 「子树元素和」 定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。
提示:
节点数在 [1, 10^4] 范围内
-105 <= Node.val <= 105
【代码】
后序遍历二叉树,计算每个当前节点的【子树元素和】,将每个节点的【子树元素和】存储在字典中,遍历完二叉树之后,对字典进行排序,按照value的从大到小进行排序,找到value的最大值,然后遍历字典所有满足这个最大值的key的列表。
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
cnt={
}
def dfs(root):
if not root:
return 0
l=dfs(root.left)
r=dfs(root.right)
root.val+=l+r
if root.val not in cnt:
cnt[root.val]=0
cnt[root.val]+=1
return root.val
dfs(root)
cnt=dict(sorted(cnt.items(),key=lambda x:-x[0]))
max_c=max(cnt.values())
return [key for key in cnt if cnt[key]==max_c]
其实这里不对字典进行排序也是可以达到相同的效果
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
cnt={
}
def dfs(root):
if not root:
return 0
l=dfs(root.left)
r=dfs(root.right)
root.val+=l+r
if root.val not in cnt:
cnt[root.val]=0
cnt[root.val]+=1
return root.val
dfs(root)
# cnt=dict(sorted(cnt.items(),key=lambda x:-x[0]))
max_c=max(cnt.values())
return [key for key in cnt if cnt[key]==max_c]
边栏推荐
猜你喜欢
随机推荐
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
墨西哥大众VW Mexico常见的几种label
中级xss绕过【xss Game】
实操|风控模型中常用的这三种预测方法与多分类场景的实现
[网鼎杯 2020 青龙组]AreUSerialz
《GB39707-2020》PDF下载
华为HCIE云计算之FC添加ipsan数据存储
高压之下,必有懦夫
数据治理(五):元数据管理
多线程之自定义线程池
[Swoole Series 3.5] Process Pool and Process Manager
[QNX Hypervisor 2.2用户手册]10.14 smmu
c# 解决CS8602告警 解引用可能出现空引用
Unity reports Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe’ code” in Pla
《GB39707-2020》PDF download
Chip Information|Semiconductor revenue growth expected to slow to 7%, Bluetooth chip demand still growing steadily
51单片机驱动HMI串口屏,串口屏的下载方式
volatile 关键字(修饰符 volatile 告诉编译器,变量的值可能以程序未明确指定的方式被改变)
网络爬虫错误
微透镜阵列后光传播的研究









