Sum of Left Leaves in Binary Tree
Given the root of a binary tree, return the sum of all left leaves.
A left leaf is a leaf that is the left child of its parent.
Function Signature:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_of_left_leaves(root: TreeNode) -> int:
"""
Calculate the sum of all left leaves in a binary tree.
Parameters:
- root: The root of the binary tree.
Returns:
- int: The sum of all left leaves.
"""
# Your code here
Example:
# Example Binary Tree:
# 6
# / \
# 8 12
# / \
# 10 5
root = TreeNode(6,
TreeNode(8),
TreeNode(12,
TreeNode(10),
TreeNode(5)
)
)
result = sum_of_left_leaves(root)
print(result)
assert result == 23
# Explanation: Sum of left leaves: 8 + 10 = 18
Note:
- The given binary tree is not necessarily a binary search tree.
- All node values are unique.
Instructions:
- Write the
sum_of_left_leaves
function to solve the problem. - Implement your solution in Python.
- Provide clear comments in your code.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊