The problem requires calculating the sum of values at the deepest level of leaves in a binary tree. To achieve this, we use Breadth-First Search (BFS) or Level Order Traversal. The idea is simple and efficient:
Traverse the tree level by level.
For each level, calculate the sum of node values.
Finally, the sum of the last level (deepest level) will be the required result.
classSolution {
publicintdeepestLeavesSum(TreeNode root) {
Queue<TreeNode> q =new LinkedList<>();
q.add(root);
int ans = 0;
while (!q.isEmpty()) {
ans = 0; // Reset the sum for the current levelint size = q.size();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
ans += node.val; // Add current node value to the sumif (node.left!=null) {
q.add(node.left); // Add left child if exists }
if (node.right!=null) {
q.add(node.right); // Add right child if exists }
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defdeepestLeavesSum(self, root: Optional[TreeNode]) -> int:
q: deque[TreeNode] = deque([root])
ans: int =0while q:
ans =0# Reset the sum for the current levelfor _ in range(len(q)): # Iterate over nodes of the current level node = q.popleft()
ans += node.val # Add current node value to the sumif node.left:
q.append(node.left) # Add left child if existsif node.right:
q.append(node.right) # Add right child if existsreturn ans
⏰ Time complexity: - O(n). We touch each node exactly once during tree traversal.
🧺 Space complexity: O(n). In the worst case, the queue can store all the nodes of the last level, and in a binary tree, the last level can have up to n/2 nodes in a full tree.