1161. 最大レイヤー要素合計
問題解決のアイデア
- 変更されたバイナリツリーのレベル順序トラバーサル
- 一時変数を設定して各レイヤーを横断し、現在のレイヤーの要素の合計を計算し、最後に最大値を取り出します
- レイヤー数を計算するための変数を設定します。
/**
* 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;
}
}