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.
1#include <iostream>
2#include <algorithm>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int maxDepth = 0;
int sum = 0;
void dfs(TreeNode* node, int depth) {
if (!node) 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);
}
int deepestLeavesSum(TreeNode* root) {
dfs(root, 0);
return sum;
}
};
The C++ solution uses DFS to traverse the binary tree. It tracks both the current depth and the maximum encountered depth to update or add to the sum accordingly.