题解 | #重量级的一层#
重量级的一层
https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c?tpId=354&tqId=10595898&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int maxLevelSum (TreeNode root) {
LinkedList<TreeNode> linkedList = new LinkedList<>();
linkedList.add(root);
int max = Integer.MIN_VALUE;
// index是层数
int index = 1;
// result是最大和的层数
int result = 1;
while (!linkedList.isEmpty()) {
int sum = 0;
// 每一层求和
for (TreeNode treeNode : linkedList) {
sum += treeNode.val;
}
// 寻找最大值并记录索引
if (sum > max) {
max = sum;
result = index;
}
// 进入下一层
index++;
int size = linkedList.size();
// 向队列添加节点,进入下层
while (size-- > 0) {
TreeNode node = linkedList.poll();
if (node.left != null) {
linkedList.add(node.left);
}
if (node.right != null) {
linkedList.add(node.right);
}
}
}
return result;
}
}
本题知识点分析:
1.二叉树层序遍历
2.集合存取
3.数学模拟
本题解题思路分析:
1.利用二叉树层序遍历
2.记录每一层的和,并与max进行比较,然后记录当前最大层的索引也就是result
3.最后返回最大层的索引result即可
本题使用编程语言:Java
如果您觉得本篇文章对您有帮助的话,可以点个赞,支持一下,感谢~

