当前位置:网站首页>LeetCode——1161. 最大层内元素和
LeetCode——1161. 最大层内元素和
2022-08-03 11:03:00 【Cap07】
题目:1161. 最大层内元素和 - 力扣(LeetCode)
package j2;
import java.util.*;
//Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int maxLevelSum(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int max = Integer.MIN_VALUE;
int level = 1;
int answer = 1;
while (!queue.isEmpty()) {
int size = queue.size();
int sum = 0;
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
sum += temp.val;
if (temp.left != null) {
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
}
if (sum > max) {
max = sum;
answer = level;
}
level++;
}
return answer;
}
}
public class j3 {
public static void main(String args[]) {
TreeNode T = new TreeNode();
T.val = 1;
T.left = new TreeNode();
T.right = new TreeNode();
T.left.val = 7;
T.right.val = 0;
T.right.left = null;
T.right.right = null;
T.left.left = new TreeNode();
T.left.right = new TreeNode();
T.left.left.val = 7;
T.left.right.val = -8;
Solution S = new Solution();
System.out.println(S.maxLevelSum(T));
}
}边栏推荐
- build --repot
- How to retrieve IDC research reports?
- Traceback (most recent call last): File
- [Output each bit of an integer, from high to low.With and without recursion]
- oracle计算同、环比
- MySQL数据库高级使用
- Web Server 设置缓存响应字段的一些推荐方案
- Advanced use of MySQL database
- 二叉搜索树(搜索二叉树)模拟实现(有递归版本)
- Babbitt | Metaverse daily must-read: Players leave, platforms are shut down, and the digital collection market is gradually cooling down. Where is the future of the industry?...
猜你喜欢
随机推荐
智能合约是什么?
【LeetCode—第2题 两数之和 代码详解 】附有源码,可直接复制
3分钟实现内网穿透(基于ngrok实现)
build --repot
深度学习100例——卷积神经网络(CNN)实现服装图像分类
如何检索IDC研究报告?
【冒泡排序以及奇数偶数排列】
MySQL数据库基本使用
嵌入式软件组件经典架构与存储器分类
Machine Learning (Chapter 1) - Feature Engineering
机器比人更需要通证
Basic using MySQL database
使用.NET简单实现一个Redis的高性能克隆版(一)
鸿蒙第三次
507. 完美数
成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...
完全背包问题
增加WebView对localStorage的支持
数据库一席谈:打造开源的数据生态,支撑产业数字化浪潮
Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million









