Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Sum of Left Leaves

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "404" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. Example 2: Input: root = [1] Output: 0 Constraints: The number of nodes in the tree is in the range [1, 1000]. -1000 <= Node.val <= 1000

Explanation

Here's the breakdown of the approach and the Python code:

  • Approach:

    • Perform a recursive traversal of the binary tree.
    • At each node, check if its left child exists and if it's a leaf node. If so, add its value to the running sum.
    • Recursively call the function on the left and right subtrees.
  • Complexity:

    • Runtime Complexity: O(N), where N is the number of nodes in the tree (we visit each node once).
    • Storage Complexity: O(H), where H is the height of the tree (due to the recursion stack). In the worst-case (skewed tree), H = N, and in the best-case (balanced tree), H = log N.

Code

    class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def sumOfLeftLeaves(root: TreeNode) -> int:
    """
    Calculates the sum of all left leaves in a binary tree.

    Args:
        root: The root node of the binary tree.

    Returns:
        The sum of all left leaves.
    """

    def is_leaf(node):
        return node is not None and node.left is None and node.right is None

    def sum_left(node, is_left_child=False):
        if not node:
            return 0

        total_sum = 0
        if node.left and is_leaf(node.left):
            total_sum += node.left.val

        total_sum += sum_left(node.left)
        total_sum += sum_left(node.right)

        return total_sum

    return sum_left(root)

More from this blog

C

Chatmagic blog

2894 posts