↓Skip to main content
  1. LeetCode/

LeetCode 112: Path Sum

·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-16

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

Approach
#

Subtract the current value from the target on the way down (Tree Template 1). At a leaf, the path works if the remaining target equals the leaf’s value. Only leaves count; hitting the sum at an internal node does not.

My Attempts
#

One version wrote root == targetSum, comparing the node itself with an integer, never equal: [5], targetSum = 5 returned False. Two others had an undefined variable and a type error.

Solution
#

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right:
            return root.val == targetSum
        rest = targetSum - root.val
        return self.hasPathSum(root.left, rest) or self.hasPathSum(root.right, rest)

Complexity
#

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

Mistakes to Avoid
#

  • Compare root.val, not the node.
  • Check only at leaves.

Interview Explanation
#

Recursing down, I subtract each value from the target and check at leaves whether the remainder equals the leaf; either side succeeding returns True. Time O(n).

Related

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 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
LeetCode 110: Balanced Binary Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 note: every node’s subtree heights must differ by at most 1; return heights in post-order and propagate -1 once unbalanced
LeetCode 144: Binary Tree Preorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 note: iterative pre-order traversal records on pop and pushes the right child before the left so the left is handled first