↓Skip to main content
  1. LeetCode/

LeetCode 404: Sum of Left Leaves

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Runtime Error → Wrong Answer ×3 → Accepted ×3

Approach
#

A left leaf needs two facts: it is a leaf, and it is its parent’s left child (Tree Template 1). Pass a boolean is_left down and decide at each leaf.

My Attempts
#

Two versions marked sides with the strings 'True' and 'False', but the string 'False' is truthy too, so right leaves were added. For [4, 6, 9] only 6 is a left leaf, answer 6; they returned 15.

Solution
#

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        def dfs(node, is_left):
            if not node:
                return 0
            if not node.left and not node.right:
                return node.val if is_left else 0
            return dfs(node.left, True) + dfs(node.right, False)
        return dfs(root, False)

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • The root is never a left leaf, even when it is a leaf.
  • Use real booleans; the string 'False' is truthy.

Interview Explanation
#

I pass an “is left child” flag during DFS and add a value only at leaves that are left children. Time O(n).

Related

LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 111: Minimum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 note: minimum depth must end at a leaf; with only one child, the empty side (depth 0) cannot count as the minimum
LeetCode 112: Path Sum
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 note: subtract each value from targetSum on the way down; it works if the remainder matches at a leaf
LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides
LeetCode 101: Symmetric Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 note: the left and right subtrees must mirror each other, outer with outer and inner with inner; compare values, not node objects
LeetCode 104: Maximum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 104 note: depth is 1 plus the larger subtree depth, with 0 for an empty tree