📅  最后修改于: 2023-12-03 15:37:14.914000             🧑  作者: Mango
This question requires a basic understanding of recursion and tree traversal.
The problem statement asks us to find the sum of all left leaves in a given binary tree.
Consider the following binary tree.
5
/ \
3 8
/ \ / \
4 2 9 1
The left leaves are 4
and 9
, so the answer would be 13
.
We can solve the problem recursively by traversing the tree and keeping track of whether a particular node is a left child or not. If it is a left child, we add its value to a running total.
Here's our approach:
null
, return 0
.Here's the code in Python:
class Node:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def sum_left_leaves(root):
if root is None:
return 0
if root.left_child and root.left_child.left_child is None and root.left_child.right_child is None:
left_sum = root.left_child.value
else:
left_sum = 0
return left_sum + sum_left_leaves(root.left_child) + sum_left_leaves(root.right_child)
Since we are traversing every node in the tree once, the time complexity of our algorithm is O(n)
, where n
is the number of nodes in the tree. Since we are not using any additional data structures, the space complexity is also O(n)
, due to the recursive call stack.
#返回markdown格式