【层序遍历】1161. 最大层内元素和

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;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/132475028