↓Skip to main content
  1. LeetCode/

LeetCode 113: Path Sum II

·2 mins· ·
LeetCode Medium Backtracking Tree Depth-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: medium First Attempt: 2022-11-18

  • Submissions: Wrong Answer → Accepted → Wrong Answer → Accepted

Approach
#

Subtract down the tree as in LC 112, but record the whole path (Backtracking): append on entering a node, save a copy at a matching leaf, and pop on leaving.

Values can be negative, so exceeding the target so far does not rule out later nodes; no pruning.

My Attempts
#

Both WAs had the same pruning: stop when targetSum - root.val < 0. Values can be negative, though: [4, -1], targetSum = 3 gives 4 - 1 = 3, so the answer is [[4, -1]]; it pruned at the root and returned nothing.

Solution
#

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        res, path = [], []
        def dfs(node, rest):
            if not node:
                return
            path.append(node.val)
            rest -= node.val
            if not node.left and not node.right and rest == 0:
                res.append(path[:])                  # 存複本
            dfs(node.left, rest)
            dfs(node.right, rest)
            path.pop()
        dfs(root, targetSum)
        return res

Complexity
#

Time O(n · h) (copying paths), space O(h).

Mistakes to Avoid
#

  • With negative values, do not prune on “already over”.
  • Store a copy, path[:].

Interview Explanation
#

I backtrack with the current path, adding each value and reducing the target on the way down, saving a copy when a leaf leaves 0, and popping on the way back. Values can be negative, so there is no pruning. Time O(n · h).

Related

LeetCode 129: Sum Root to Leaf Numbers
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Tree
LeetCode 129 note: on the way down multiply the current number by 10 and add the node’s value, adding it to the total at a leaf
LeetCode 236: Lowest Common Ancestor of a Binary Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Tree Binary-Lifting
LeetCode 236 note: recursion returns whichever of p or q a subtree contains; finding something on both sides means they split here, so this node is the LCA
LeetCode 337: House Robber III
·2 mins
LeetCode Medium Dynamic-Programming Tree Depth-First-Search Binary-Tree
LeetCode 337 note: tree DP where each node returns the best (rob it, skip it) pair; not robbing alternate levels
LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum
LeetCode 199: Binary Tree Right Side View
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 note: in a level-order traversal, each level’s rightmost node is what you see from the right
LeetCode 230: Kth Smallest Element in a BST
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 230 note: a BST’s in-order traversal is ascending, so stop an iterative in-order walk at the k-th node