当前位置:网站首页>[1161. The maximum sum of elements in the layer]
[1161. The maximum sum of elements in the layer]
2022-07-31 23:22:00 【[email protected]】
来源:力扣(LeetCode)
描述:
给你一个二叉树的根节点 root.设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推.
请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个.
示例 1:

输入: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, 104]范围内
- -105 <= Node.val <= 105
方法一:深度优先搜索
We can traverse this binary tree using a depth-first search,The current layer number is recorded at the same time recursively.
相比哈希表,Here we use a more efficient dynamic array to maintain the sum of the elements of each layer,If the current layer number reaches the length of the array,then add the node element to the end of the array,Otherwise, update the sum of the elements corresponding to the layer number.
然后遍历数组,Find the maximum sum of elements,and the element with the smallest layer number.
代码:
class Solution {
vector<int> sum;
void dfs(TreeNode *node, int level) {
if (level == sum.size()) {
sum.push_back(node->val);
} else {
sum[level] += node->val;
}
if (node->left) {
dfs(node->left, level + 1);
}
if (node->right) {
dfs(node->right, level + 1);
}
}
public:
int maxLevelSum(TreeNode *root) {
dfs(root, 0);
int ans = 0;
for (int i = 0; i < sum.size(); ++i) {
if (sum[i] > sum[ans]) {
ans = i;
}
}
return ans + 1; // layer number from 1 开始
}
};
执行用时:144 ms, 在所有 C++ 提交中击败了94.63%的用户
内存消耗:102.2 MB, 在所有 C++ 提交中击败了97.01%的用户
复杂度分析
时间复杂度: O(n),其中 n 是二叉树的节点个数.
空间复杂度: O(n).The worst case binary tree is a chain,需要 O(n) the array space as well O(n) 的递归栈空间.
方法二:广度优先搜索
Since the calculation is the sum of the elements of each layer,It would be more natural to traverse the tree with a breadth-first search.
For breadth-first search,We can do this with queues.初始时,The queue contains only the root node;然后不断出队,将子节点入队,直到队列为空.
If you directly apply the idea of Method 1,We need to store the node and the layer number of the node in the queue.Another way to do this is to traverse a full layer of nodes at a time,遍历的同时,Accumulates the element-wise sum of the nodes of this layer,At the same time, use the nodes of this layer to get the nodes of the next layer,This practice does not require recording layer numbers.
为了代码实现的方便,We can use two dynamic arrays,第一个数组 q is the node of the current layer,第二个数组 nq is the node of the next layer.遍历 q at the same time as the middle node,Add child nodes to nq 中.After traversing the current layer,将 q 置为 nq.
代码:
class Solution {
public:
int maxLevelSum(TreeNode *root) {
int ans = 1, maxSum = root->val;
vector<TreeNode*> q = {
root};
for (int level = 1; !q.empty(); ++level) {
vector<TreeNode*> nq;
int sum = 0;
for (auto node : q) {
sum += node->val;
if (node->left) {
nq.emplace_back(node->left);
}
if (node->right) {
nq.emplace_back(node->right);
}
}
if (sum > maxSum) {
maxSum = sum;
ans = level;
}
q = move(nq);
}
return ans;
}
};
执行用时:152 ms, 在所有 C++ 提交中击败了84.78%的用户
内存消耗:109 MB, 在所有 C++ 提交中击败了6.87%的用户
复杂度分析
时间复杂度: O(n),其中 n 是二叉树的节点个数.
空间复杂度: O(n).最坏情况下,数组中有 O(n) 个节点.
author:LeetCode-Solution
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/212/202207312314447000.html
边栏推荐
- HTC using official firmware as bottom bag made ROM brush card bag tutorial
- 编写方法将一个数组扁平化并且去重和递增排序
- 10大主流3D建模技术
- #yyds dry goods inventory# Interview must brush TOP101: the entry node of the ring in the linked list
- IPD流程专业术语
- 什么是动态规划,什么是背包问题
- 基于mysql的消息队列设计
- /etc/sysconfig/network-scripts 配置网卡
- IDA PRO中汇编结构体识别
- 输入输出优化
猜你喜欢

The article you worked so hard to write may not be your original

Shell common scripts: Nexus batch upload local warehouse enhanced version script (strongly recommended)

UOS - WindTerm use

Interview assault 69: TCP reliable?Why is that?

Collation of knowledge points in Ningbo University NBU IT project management final exam

leetcode:126. 单词接龙 II

C# Rectangle基本用法和图片切割

一文带你了解 Grafana 最新开源项目 Mimir 的前世今生

How to reduce the gap between software design and implementation

Unity-LineRenderer显示一条线
随机推荐
IDA PRO中汇编结构体识别
Golang must know the Go Mod command
TestCafeSummary
高等代数_证明_任何矩阵都相似于一个上三角矩阵
Flutter教程之 01配置环境并运行demo程序 (教程含源码)
Shell common script: Nexus batch upload local warehouse script
PHP三元(三目)运算符
编写方法将一个数组扁平化并且去重和递增排序
Shell常用脚本:Nexus批量上传本地仓库增强版脚本(强烈推荐)
Quick Start Tutorial for flyway
硬件设备计算存储及数据交互杂谈
博弈论(Depu)与孙子兵法(42/100)
助力数字政府建设,中科三方构建域名安全保障体系
手写一个简单的web服务器(B/S架构)
Pytest first experience
日常--Kali开启SSH(详细教程)
In Golang go-redis cluster mode, new connections are constantly created, and the problem of decreased efficiency is solved
[QNX Hypervisor 2.2 User Manual]9.16 system
lua入门案例实战1234定义函数与标准函数库功能
UOS统信系统 - WindTerm使用