Sponsored
Sponsored
This approach leverages a Breadth-First Search (BFS) traversal method using a queue to explore each level of the binary tree fully before moving on to the next level. By summing values at each level during the traversal, we can determine the sum of the deepest leaves by replacing the sum at every level.
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Space Complexity: O(n), for storing nodes in the queue.
1import java.util.LinkedList;
2import java.util.Queue;
3
4class TreeNode {
5 int val;
6 TreeNode left;
7 TreeNode right;
8 TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12 public int deepestLeavesSum(TreeNode root) {
13 if (root == null) return 0;
14
15 Queue<TreeNode> queue = new LinkedList<>();
16 queue.offer(root);
17 int sum = 0;
18
19 while (!queue.isEmpty()) {
20 int size = queue.size();
21 sum = 0;
22 for (int i = 0; i < size; i++) {
23 TreeNode node = queue.poll();
24 sum += node.val;
25 if (node.left != null) queue.offer(node.left);
26 if (node.right != null) queue.offer(node.right);
27 }
28 }
29
30 return sum;
31 }
32}
The Java solution follows the BFS method to traverse each tree level completely while summing the node values. The resultant sum post loop execution is the deepest leaves' sum.
This alternative approach uses Depth-First Search (DFS) to traverse the binary tree and keeps track of the maximum depth and accumulated sum of the node values at that depth.
Time Complexity: O(n)
Space Complexity: O(h), where h is the height of the tree due to recursion stack.
1using System;
2
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
private int maxDepth = 0;
private int sum = 0;
private void DFS(TreeNode node, int depth) {
if (node == null) return;
if (depth > maxDepth) {
maxDepth = depth;
sum = node.val;
} else if (depth == maxDepth) {
sum += node.val;
}
DFS(node.left, depth + 1);
DFS(node.right, depth + 1);
}
public int DeepestLeavesSum(TreeNode root) {
DFS(root, 0);
return sum;
}
}
C# solution runs a similar DFS, tracking max depth and adjusting sums in a depth-first traversal manner, using recursion.