KatInterview

113. Path Sum II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all paths from the root of a binary tree to any of its leaves such that the sum of the node values along the path equals a given targetSum. A leaf is a node with no children. We need to return these paths as a list of lists of node values.

Solution

Path Sum II in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        result = []
        
        def find_paths(node, remaining_sum, current_path):
            # If the current node is None, we've reached a dead end.
            if not node:
                return

            # Add the current node to the path.
            current_path.append(node.val)

            # Check if it's a leaf node and the sum matches.
            if not node.left and not node.right and remaining_sum == node.val:
                # Found a valid path. Add a copy of the path to the result.
                # Using current_path[:] creates a shallow copy.
                result.append(list(current_path))
            else:
                # Recursively search in left and right subtrees.
                find_paths(node.left, remaining_sum - node.val, current_path)
                find_paths(node.right, remaining_sum - node.val, current_path)
            
            # Backtrack: remove the current node from the path to explore other branches.
            current_path.pop()

        find_paths(root, targetSum, [])
        return result

Path Sum II in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> currentPath = new ArrayList<>();
        findPaths(root, targetSum, currentPath, result);
        return result;
    }

    private void findPaths(TreeNode node, int sum, List<Integer> currentPath, List<List<Integer>> result) {
        // If the current node is null, we've reached a dead end.
        if (node == null) {
            return;
        }

        // Add the current node's value to the path.
        currentPath.add(node.val);

        // Check if the current node is a leaf and if the path sum equals the target sum.
        if (node.left == null && node.right == null && sum == node.val) {
            // If it is, we've found a valid path. Add a copy of it to the result list.
            // It's crucial to create a new ArrayList to copy the path, otherwise
            // subsequent backtracking will modify the path in the result list.
            result.add(new ArrayList<>(currentPath));
        } else {
            // Recursively search in the left and right subtrees.
            // Subtract the current node's value from the sum for the next level.
            findPaths(node.left, sum - node.val, currentPath, result);
            findPaths(node.right, sum - node.val, currentPath, result);
        }

        // Backtrack: remove the current node from the path to explore other branches.
        currentPath.remove(currentPath.size() - 1);
    }
}

Path Sum II in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<vector<int>> result;
        vector<int> currentPath;
        findPaths(root, targetSum, currentPath, result);
        return result;
    }

private:
    void findPaths(TreeNode* node, int sum, vector<int>& currentPath, vector<vector<int>>& result) {
        // If the current node is null, we've reached a dead end.
        if (!node) {
            return;
        }

        // Add the current node's value to the path.
        currentPath.push_back(node->val);

        // Check if the current node is a leaf and if the path sum equals the target sum.
        if (!node->left && !node->right && sum == node->val) {
            // If it is, we've found a valid path. Add it to the result list.
            // A copy of currentPath is made automatically when pushed back.
            result.push_back(currentPath);
        }

        // Recursively search in the left and right subtrees.
        // Subtract the current node's value from the sum for the next level.
        findPaths(node->left, sum - node->val, currentPath, result);
        findPaths(node->right, sum - node->val, currentPath, result);

        // Backtrack: remove the current node from the path to explore other branches.
        currentPath.pop_back();
    }
};

Path Sum II in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function pathSum(root: TreeNode | null, targetSum: number): number[][] {
    const result: number[][] = [];

    function findPaths(node: TreeNode | null, sum: number, currentPath: number[]) {
        // If the current node is null, we've reached a dead end.
        if (!node) {
            return;
        }

        // Add the current node's value to the path.
        currentPath.push(node.val);

        // Check if the current node is a leaf and if the path sum equals the target sum.
        if (node.left === null && node.right === null && sum === node.val) {
            // If it is, we've found a valid path. Add a copy of it to the result list.
            // Using the spread syntax `[...currentPath]` creates a shallow copy.
            result.push([...currentPath]);
        } else {
            // Recursively search in the left and right subtrees.
            // Subtract the current node's value from the sum for the next level.
            findPaths(node.left, sum - node.val, currentPath);
            findPaths(node.right, sum - node.val, currentPath);
        }

        // Backtrack: remove the current node from the path to explore other branches.
        currentPath.pop();
    }

    findPaths(root, targetSum, []);
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.