当前位置:网站首页>[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
边栏推荐
- (26) About menu of the top menu of Blender source code analysis
- How to reduce the gap between software design and implementation
- 逐步手撕轮播图3(保姆级教程)
- Flutter教程之 02 Flutter 桌面程序开发入门教程运行hello world (教程含源码)
- 内核对设备树的处理
- 编程语言是什么
- Unity-通过预制件和克隆方法动态实现各个UGUI下控件的创建和显示
- ICML2022 | 深入研究置换敏感的图神经网络
- HTC使用官方固件作为底包制作rom卡刷包教程
- Drawing process of hand-drawn map of scenic spots
猜你喜欢
cobaltstrike
Shell common script: Nexus batch upload local warehouse script
Recognize anomalies (you will understand after reading this)
高等代数_证明_任何矩阵都相似于一个上三角矩阵
TestCafeSummary
IDA PRO中汇编结构体识别
Bionic caterpillar robot source code
网易云信圈组上线实时互动频道,「破冰」弱关系社交
The latest masterpiece!Alibaba just released the interview reference guide (Taishan version), I just brushed it for 29 days
Document management and tools in the development process
随机推荐
Pytest初体验
二叉树非递归遍历
Payment module implementation
Audio alignment using cross-correlation
「SDOI2016」征途 题解
编写方法将一个数组扁平化并且去重和递增排序
SQL injection Less42 (POST type stack injection)
标段参数说明
基于mysql的消息队列设计
10大主流3D建模技术
SQL注入 Less54(限制次数的SQL注入+union注入)
字符编码和浮点型计算精度丢失问题
Pytest first experience
The difference between adding or not adding the ref keyword when a variable of reference type is used as a parameter in a method call in C#
[QNX Hypervisor 2.2 User Manual]9.14 set
【Acwing】The 62nd Weekly Game Solution
支付模块实现
/etc/resolv.conf的作用
cobaltstrike
Mysql environment installation under Linux (centos)