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.
1#include <iostream>
2#include <queue>
3
4struct TreeNode {
5 int val;
6 TreeNode* left;
7 TreeNode* right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11int deepestLeavesSum(TreeNode* root) {
12 if (!root) return 0;
13 std::queue<TreeNode*> q;
14 q.push(root);
15 int sum = 0;
16
17 while (!q.empty()) {
18 int size = q.size();
19 sum = 0;
20 for (int i = 0; i < size; ++i) {
21 TreeNode* node = q.front();
22 q.pop();
23 sum += node->val;
24 if (node->left) q.push(node->left);
25 if (node->right) q.push(node->right);
26 }
27 }
28
29 return sum;
30}
The solution uses a queue to perform a level order traversal. At each level, it clears the previous sum and computes the new sum for the current level. After the last level is processed, the sum contains the sum of the deepest leaves.
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.