1302. Deepest Leaves Sum

1302. Deepest Leaves Sum

Given a binary tree, return the sum of values of its deepest leaves.

 

Example 1:

1302. Deepest Leaves Sum_第1张图片

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

 

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.
class Solution {
  public int deepestLeavesSum(TreeNode root) {
        int res=0;
        if(root == null) return 0;
        LinkedList togo = new LinkedList();
        togo.add(root);
        while(!togo.isEmpty())
        {
            res=0; // starting a new level
            
            for(int sz=togo.size()-1;sz>=0;sz--) {
                TreeNode node = togo.poll();
                res += node.val;
                if(node.left  != null) togo.add(node.left);
                if(node.right != null) togo.add(node.right);
                
            }
            System.out.println(res);
        }
        return res;
    }
}

最后一层加完的时候queue恰好为空,此时res就是最后一层的值。

public int deepestLeavesSum(TreeNode root) {
        int res = 0, i;
        LinkedList q = new LinkedList();
        q.add(root);
        while (!q.isEmpty()) {
            for (i = q.size() - 1, res = 0; i >= 0; --i) {
                TreeNode node = q.poll();
                res += node.val;
                if (node.right != null) q.add(node.right);
                if (node.left  != null) q.add(node.left);
            }
        }
        return res;
    }

每次进入for循环都是上一层的queue在工作,循环结束了res已经更新,同时下一层的元素也已经加到queue中,直到最后一层为止。

你可能感兴趣的:(1302. Deepest Leaves Sum)