[Binary tree] 1302. The sum of the deepest leaf nodes

1302. The sum of the deepest leaf nodes in layers

problem solving ideas

  • The layer order traversal algorithm of reformed binary tree accumulates the sum of the last layer
  • Similar to calculating the sum of each layer of a binary tree
/**
 * 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 deepestLeavesSum(TreeNode root) {
    
    
        // 改造二叉树的层序遍历算法  累加最后一层的和
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
    
    
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<>();// 使用双向链表可以模拟栈结构
        q.offer(root);
        int sum = 0;

        while(!q.isEmpty()){
    
    
            // 计算此时队列的大小
            int size =  q.size();
            sum = 0;

            for(int i = 0; i < size; i++){
    
    
                // 取出当前队列头部节点
                TreeNode cur = q.poll();
                sum += cur.val;
                if(cur.left != null){
    
    
                    q.offer(cur.left);
                }

                if(cur.right != null){
    
    
                    q.offer(cur.right);
                }
            }
        }


        return sum;
    }
}


Guess you like

Origin blog.csdn.net/qq_44653420/article/details/132487584