码迷,mamicode.com
首页 > 其他好文 > 详细

1302. Deepest Leaves Sum

时间:2020-01-30 12:59:39      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:node   leaves   tin   https   upload   treenode   inpu   com   src   

1302. Deepest Leaves Sum

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

 

Example 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<TreeNode> togo = new LinkedList<TreeNode>();
        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<TreeNode> q = new LinkedList<TreeNode>();
        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

标签:node   leaves   tin   https   upload   treenode   inpu   com   src   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12242457.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!