当前位置:网站首页>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));
}
}
边栏推荐
- 在 Chrome 开发者工具里通过 network 选项模拟网站的离线访问模式
- 再谈“雷克萨斯”安全装置失效!安全手册疑点重重,网友:细思极恐
- 微信小程序获取用户手机号码
- 干货!一种被称为Deformable Butterfly(DeBut)的高度结构化且稀疏的线性变换
- 基于PHP7.2+MySQL5.7的回收租凭系统
- 通过GBase 8c Platform安装数据库集群时报错
- BPMN和DMN基本概念和使用案例
- How to use outside the PHP command in the container
- Skills required to be a good architect: How to draw a system architecture that everyone will love?What's the secret?Come and open this article to see it!...
- Why is the new earth blurred, in-depth analysis of white balls, viewing pictures, and downloading problems
猜你喜欢
随机推荐
直播弱网优化
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二
[Explanation of JDBC and inner classes]
多态详细讲解(简单实现买票系统模拟,覆盖/重定义,多态原理,虚表)
玉溪卷烟厂通过正确选择时序数据库 轻松应对超万亿行数据
跨链桥协议 Nomad 遭遇黑客攻击,损失超 1.5 亿美元
通过GBase 8c Platform安装数据库集群时报错
【TypeScript】Why choose TypeScript?
程序员架构修炼之道:如何设计出可持续演进的系统架构?
Matplotlib
C#/VB.NET 从PDF中提取表格
Depth study of 100 cases - convolution neural network (CNN) to realize the clothing image classification
请问应该用什么关键字将内容主题设置为 dark 呢
如何通过DBeaver 连接 TDengine?
MATLAB programming and application 2.7 Structural data and unit data
ERC20通证标准是什么?
Basic using MySQL database
FR9811S6 SOT-23-6 23V,2A同步降压DC/DC转换器
实现2d人物在跳跃的同时左右移动
The way of programmer architecture practice: how to design a sustainable evolution system architecture?