Question
Given the root
of a binary tree, return the sum of values of its deepest leaves.
Solution
BFS搜索,层序遍历,每次计算每个层级的总和。
最后返回最后一个层级总和。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { public int deepestLeavesSum(TreeNode root) { Deque<TreeNode> q = new LinkedList<>(); int res = 0; q.offer(root); int level = q.size(); while(!q.isEmpty()){ int sum = 0; for(int i = 0; i < level; i++){ TreeNode curr = q.poll(); sum += curr.val; if(curr.left != null) q.offer(curr.left); if(curr.right != null) q.offer(curr.right); } res = sum; level = q.size(); } return res; } }
|