root
of a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15
Example 2:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19
Constraints:
[1, 104]
.1 <= Node.val <= 100
The problem asks for the sum of values of the deepest leaves in a binary tree. Two approaches are efficient: Breadth-First Search (BFS) and Depth-First Search (DFS).
BFS is an iterative approach that explores the tree level by level. We use a queue to keep track of nodes to visit.
Algorithm:
ans
).ans
represents the sum of values at the deepest level.Time Complexity: O(N), where N is the number of nodes. Each node is visited and processed exactly once.
Space Complexity: O(W), where W is the maximum width (number of nodes) at any level of the tree. In the worst case (a complete binary tree), W can be proportional to N.
DFS is a recursive approach that explores the tree branch by branch. We maintain the maximum depth seen so far and the sum of nodes at that depth.
Algorithm:
max_depth
keeps track of the deepest level encountered, and sum
stores the sum of nodes at that level. We start with max_depth = 0
and sum = 0
.dfs
function recursively visits nodes.max_depth
.
max_depth
, it's a new deepest level. Update max_depth
and set sum
to the node's value.max_depth
, add the node's value to sum
.sum
holds the desired result.Time Complexity: O(N), as each node is visited once.
Space Complexity: O(H) in the worst case, where H is the height of the tree. This is due to the recursive call stack. In a skewed tree, H can be N. However, in a balanced tree, H is log₂N.
BFS:
from collections import deque
def deepestLeavesSum(root):
q = deque([root])
ans = 0
while q:
level_sum = 0
for _ in range(len(q)):
node = q.popleft()
level_sum += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans = level_sum # Update ans with the sum of the current level
return ans
DFS:
def deepestLeavesSum(root):
max_depth = 0
sum_at_depth = 0
def dfs(node, depth):
nonlocal max_depth, sum_at_depth
if not node:
return
if depth > max_depth:
max_depth = depth
sum_at_depth = node.val
elif depth == max_depth:
sum_at_depth += node.val
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 0)
return sum_at_depth
Note: Both BFS and DFS solutions provide optimal time complexity. The choice between them often depends on factors like memory constraints (BFS might be preferred for very wide trees) and coding style preference. The provided code examples are in Python, but similar implementations are possible in other languages (Java, C++, JavaScript, etc.). Remember to adapt the code based on your specific tree node structure.