#404

Sum of Left Leaves

Easy
TreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal approach uses a single traversal of the tree while keeping track of whether a node is a left child. This avoids unnecessary checks and reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a depth-first search (DFS) approach, passing a boolean indicating whether the current node is a left child.
  2. 2Step 2: If the current node is null, return 0.
  3. 3Step 3: If the current node is a left leaf (it has no children), return its value.
  4. 4Step 4: Recursively call the function for the left and right children, summing the results.
solution.py13 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8def sumOfLeftLeaves(root, is_left=False):
9    if not root:
10        return 0
11    if not root.left and not root.right and is_left:
12        return root.val
13    return sumOfLeftLeaves(root.left, True) + sumOfLeftLeaves(root.right, False)

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Understanding the structure of binary trees is crucial.
  • 2Recognizing leaf nodes and their relationships helps in solving tree problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.