LeetCode——1161. The sum of elements in the largest layer

Title description:

Give you the root node of a binary tree. Suppose the root node is located at the first level of the binary tree, and the child nodes of the root node are located at the second level, and so on.
Please find the layer number of the layer with the largest sum of elements in the layer (maybe only one layer), and return the smallest one.

prompt:

  • The number of nodes in the tree is between 1 and 10^4
  • -10^5 <= node.val <= 10^5

Example 1:

Insert picture description here

Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation:
The sum of the elements in the
first level is 1, the sum of the elements in the second level is 7 + 0 = 7, and
the The sum of the elements in layer 3 is 7 + -8 = -1,
so we return the layer number of layer 2, which has the largest sum of elements in the layer.

Example 2:
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2

code show as below:

/**
 * 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;
        }
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int max = Integer.MIN_VALUE;
        int sign = 1;
        int ans = 0;
        while (!que.isEmpty()) {
    
    
            List<Integer> r = new ArrayList<>();
            int size = que.size();
            int sum = 0;
            for (int i = 0; i < size; i++) {
    
    
                TreeNode t = que.poll();
                r.add(t.val);
                if (t.left != null) {
    
    
                    que.offer(t.left);
                }
                if (t.right != null) {
    
    
                    que.offer(t.right);
                }
            }
            for (int i = 0; i < r.size(); i++) {
    
    
                sum += r.get(i);
            }
            if (sum > max) {
    
    
                max = sum;
                ans = sign;
            }
            sign++;
        }
        return ans;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114677907