题解 | #重量级的一层#
重量级的一层
https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c
题目考察的知识点
仍然考察的是二叉树的广度优先遍历
题目解答方法的文字分析
和前两道题目没什么太大的变化,直接将广度优先遍历的代码写上去后改编下就可以了,用high记录当前到了哪一高度,res代表要返回的值(值最大的层的高度),maxWeight记录当前访问下的最大重量和,访问到新一层的时候判断是否更新maxWeight即可,最终返回res。
本题解析所用的编程语言
使用Java语言
完整且正确的编程代码
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) {
// write code here
int high = 0, maxWeight = -1, res = 0; // high 遍历到的层的高度
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>(); //队列 数据类型是TreeNode
queue.offer(root); //加入节点
while (!queue.isEmpty()) {
int currentWeight = 0;
int currentLevelSize = queue.size();
for (int i = 1; i <= currentLevelSize; ++i) {
TreeNode node = queue.poll();
currentWeight += node.val;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
high++;
if(currentWeight>=maxWeight){
maxWeight = currentWeight;
res = high;
}
}
return res;
}
}
查看23道真题和解析
腾讯成长空间 5970人发布