标签: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:
1
and 10^4
.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中,直到最后一层为止。
标签:node leaves tin https upload treenode inpu com src
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12242457.html