LeetCode 1302: Deepest Leaves Sum Solution
Master LeetCode problem 1302 (Deepest Leaves Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1302. Deepest Leaves Sum
Problem Explanation
Explanation
To find the sum of values of the deepest leaves in a binary tree, we can perform a level order traversal of the tree. At each level, we calculate the sum of values of nodes in that level. Finally, we return the sum of values of the nodes in the last level (deepest leaves).
Algorithm:
- Initialize a queue to perform level order traversal.
- Add the root node to the queue.
- While the queue is not empty, do the following:
- Initialize a variable
levelSumto store the sum of values of nodes at the current level. - Iterate through all the nodes at the current level, updating
levelSumand adding their children to the queue.
- Initialize a variable
- Return the
levelSumcalculated in the last level.
Time Complexity:
The time complexity of this algorithm is O(N), where N is the number of nodes in the binary tree.
Space Complexity:
The space complexity of this algorithm is O(N), where N is the number of nodes in the binary tree.
Solution Code
class Solution {
public int deepestLeavesSum(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int levelSum = 0;
while (!queue.isEmpty()) {
levelSum = 0;
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
levelSum += node.val;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return levelSum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1302 (Deepest Leaves Sum)?
This page provides optimized solutions for LeetCode problem 1302 (Deepest Leaves Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1302 (Deepest Leaves Sum)?
The time complexity for LeetCode 1302 (Deepest Leaves Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1302 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1302 in Java, C++, or Python.