LeetCode #1161 Maximum Level Sum of a Binary Tree 最大层内元素和

计算机软件开发 2024-9-6 11:45:13 63 0 来自 中国
1161 Maximum Level Sum of a Binary Tree 最大层内元素和

Description:
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
Example:
Example 1:
[图片上传失败...(image-de28a8-1656336856922)]
Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Example 2:
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2
Constraints:
The number of nodes in the tree is in the range [1, 10^4].
-10^5 <= Node.val <= 10^5
标题形貌:
给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
请返回层内元素之和 最大 的那几层(大概只有一层)的层号,并返回此中 最小 的谁人。
示例 :
示例 1:
[图片上传失败...(image-427b2d-1656336856922)]
输入:root = [1,7,0,7,-8,null,null]
输出:2
表明:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
以是我们返回第 2 层的层号,它的层内元素之和最大。
示例 2:
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2
提示:
树中的节点数在 [1, 10^4]范围内
-10^5 <= Node.val <= 10^5
思绪:
层序遍历
可以用迭代大概递归
记录每一层的和及对应层数输出最大的和的层的编号
时间复杂度为 O(n), 空间复杂度为 O(n)
代码:
C++:
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-19 04:32, Processed in 0.169529 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表