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.
1class TreeNode {
2 constructor(val = 0, left = null, right = null) {
3 this.val = val;
4 this.left = left;
5 this.right = right;
6 }
7}
8
9var deepestLeavesSum = function(root) {
10 if (!root) return 0;
11
12 let queue = [root];
13 let sum = 0;
14
15 while (queue.length > 0) {
16 sum = 0;
17 let size = queue.length;
18
19 for (let i = 0; i < size; i++) {
20 const node = queue.shift();
21 sum += node.val;
22 if (node.left !== null) queue.push(node.left);
23 if (node.right !== null) queue.push(node.right);
24 }
25 }
26
27 return sum;
28};
This JavaScript function also uses a BFS-based approach with a queue to track nodes level by level. The final sum recorded after the loop reflects 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.
1class
The Java solution applies DFS to compute the sum of the deepest leaves using a recursive helper function to track the depth and adjust the sum.