📌  相关文章
📜  国际空间研究组织 | ISRO CS 2013 |问题 40(1)

📅  最后修改于: 2023-12-03 15:37:14.914000             🧑  作者: Mango

ISRO CS 2013 - Question 40

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.

Example

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.

Approach

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:

  1. Traverse the tree recursively.
  2. If the current node is null, return 0.
  3. If the current node has a left child that is a leaf node, add its value to the running total.
  4. Add the sum of the left subtree to the sum of the right subtree.
  5. Return the running total.

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)
Complexity Analysis

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格式