leetcode 1302. 层数最深叶子节点的和

给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。

 

示例 1:

 

输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
示例 2:

输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19
 

提示:

树中节点数目在范围 [1, 104] 之间。
1 <= Node.val <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/deepest-leaves-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

树的层序遍历,每一层都计算一下综合,直到最后一层,返回结果。用时间来换空间。

/**
 * 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) {
        Queue<TreeNode> a = new ArrayDeque<>();
        Queue<TreeNode> b = new ArrayDeque<>();
        a.add(root);
        while (!a.isEmpty() ) {
            int sum = 0;
            while (!a.isEmpty()) {
                TreeNode poll = a.poll();
                if (poll.left != null) {
                    b.add(poll.left);
                }
                if (poll.right != null) {
                    b.add(poll.right);
                }
                sum += poll.val;
            }
            if (b.isEmpty()) {
                
                return sum;
            }
            a = b;
            b = new ArrayDeque<>();
        }
        return 0;
    }
}

 

posted @ 2021-05-18 14:56  旺仔古李  阅读(47)  评论(0编辑  收藏  举报