题解 | #重量级的一层#
重量级的一层
https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c
知识点
树,层序遍历
解题思路
用两个队列层序遍历每一层,用max记录最大值,遍历每一层时用num来累加当前层值,i来记录当前层数。当num大于等于max时,用ans记录当前层数,更新max的值。最总结果就是ans记录的层数。
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 Deque<TreeNode> outer = new LinkedList<>(); Deque<TreeNode> inner = new LinkedList<>(); if(root != null) outer.offerFirst(root); int ans = 0; int i = 0; int max = 0; while (!outer.isEmpty()){ i++; while(!outer.isEmpty()){ inner.offerFirst(outer.pollLast()); } int num = 0; while(!inner.isEmpty()){ TreeNode treeNode = inner.pollLast(); num += treeNode.val; if(treeNode.left != null) outer.offerFirst(treeNode.left); if(treeNode.right != null) outer.offerFirst(treeNode.right); } if(num >= max) { ans = i; max = num; } } return ans; } }