Sum of Left Leaves - Complete Solution Guide
Sum of Left Leaves is LeetCode problem 404, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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
Detailed Explanation
The problem asks us to find the sum of all left leaves in a given binary tree. A left leaf is defined as a node that is both a leaf (has no children) and is the left child of its parent. The input is the root of the binary tree, and the output is an integer representing the sum of the values of all left leaves in the tree.
Solution Approach
The provided solution uses a recursive depth-first search (DFS) approach to traverse the binary tree. For each node, it checks if its left child is a leaf node. If it is, the value of the left child is added to the sum. The function then recursively calls itself on the left and right subtrees, accumulating the sum of left leaves from both subtrees. The final sum is returned.
Step-by-Step Algorithm
- Step 1: Check if the current node (root) is null. If it is, return 0 (base case).
- Step 2: Initialize a variable `sum` to 0. This variable will store the sum of left leaves.
- Step 3: Check if the current node has a left child. If it does, proceed to the next step; otherwise, skip to step 5.
- Step 4: If the left child is a leaf node (i.e., it has no left and no right children), add its value to `sum`. This is the key step to identify and count left leaves.
- Step 5: Recursively call the `sumOfLeftLeaves` function on the left subtree and add the returned value to `sum`.
- Step 6: Recursively call the `sumOfLeftLeaves` function on the right subtree and add the returned value to `sum`.
- Step 7: Return the final `sum`.
Key Insights
- Insight 1: The definition of a 'left leaf' is crucial. We need to identify nodes that are leaves AND are the left children of another node.
- Insight 2: A recursive approach is well-suited for traversing the binary tree and checking each node.
- Insight 3: Base case for recursion: If the root is null, the sum of left leaves is 0.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(h)
Topics
This problem involves: Tree, Depth-First Search, Breadth-First Search, Binary Tree.
Companies
Asked at: Grammarly.