1161. Maximum Layer Element Sum
problem solving ideas
- Level order traversal of modified binary tree
- Set a temporary variable to traverse each layer, calculate the sum of the elements of the current layer, and finally take out a maximum value
- Set a variable to calculate the number of layers
/**
* Definition for a binary tree node.
* public 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) {
if(root == null){
return 0;
}
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
// int minNum = 0;
int sum = Integer.MIN_VALUE;
int depth = 1;// 记录当前层的序号
// int depthSum = 0;// 记录当前层的和
int res = 0;// 记录结果
while(!q.isEmpty()){
int size = q.size();
// 存储当前层的节点
// List<Integer> temp = new LinkedList<>();
int depthSum = 0;
for(int i = 0; i < size; i++){
TreeNode cur = q.poll();
// temp.add(cur.val);
depthSum += cur.val;// 累加当前层的结果
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
}
// 计算最小值
if(depthSum > sum){
// 记录层的最大和
sum = depthSum;
res = depth;
}
depth++;
}
return res;
}
}