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.
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.