Question: Given the root of a binary tree, return the sum of values of its deepest leaves.
Link to the actual Question
#Solution This question is a binary tree one that looks similar to most binary trees that has something to do with leaves and depth. The number one thing to understand is the word leaves. Leaves are basically a node without children. If you look at the image above you will notice the nodes with values 7,8 and 5 are leaves thus they don't have any children.
The question wants us to return the sum of the deepest leaves that is node with value 7 and node with 8 therefore 8+7 = 15 .
They are the deepest because they are both on level 4 while node 5 is on level 3.
class Solution {
public int deepestLeavesSum(TreeNode root) {
if(root ==null)return 0;
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int result = 0;
var isLast = true;
while(!q.isEmpty()){
int size = q.size();
var leaves = 0;
while(size-- > 0){
TreeNode node = q.poll();
leaves +=node.val;
if(node.left !=null){
q.offer(node.left);
isLast = false;
}
if(node.right !=null){
q.offer(node.right);
isLast = false;
}
}
result = leaves;
}
return result;
}
}
#personalJournal #LearningByExplaining #BFS