Algo-Sim › Binary Trees & BST

Path Sum II

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Backtracking down the tree with one path list: add on the way down, copy it at a matching leaf, remove on the way back.

Problem

Given the root of a binary tree and targetSum, return every root-to-leaf path whose values add up to targetSum, each as a list of node values.

Constraints

Edge cases to test

Follow-up questions

Why copy the path at a leaf?
The list is shared and changes as the search backtracks; storing it by reference would lose the result.
What is the cost?
O(n·h) in the worst case: copying a path of length h at up to n/2 leaves.

Solution

Java

public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
    List<List<Integer>> paths = new ArrayList<>();
    walk(root, targetSum, new ArrayList<>(), paths);
    return paths;
}

private void walk(TreeNode node, int remaining, List<Integer> path, List<List<Integer>> paths) {
    if (node == null) return;
    path.add(node.val);
    remaining -= node.val;
    if (node.left == null && node.right == null && remaining == 0) {
        paths.add(new ArrayList<>(path));
    }
    walk(node.left, remaining, path, paths);
    walk(node.right, remaining, path, paths);
    path.remove(path.size() - 1);
}

Python

def path_sum(root, target_sum):
    paths = []
    walk(root, target_sum, [], paths)
    return paths


def walk(node, remaining, path, paths):
    if not node:
        return
    path.append(node.val)
    remaining -= node.val
    if not node.left and not node.right and remaining == 0:
        paths.append(path[:])
    walk(node.left, remaining, path, paths)
    walk(node.right, remaining, path, paths)
    path.pop()

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
        vector<vector<int>> paths;
        vector<int> path;
        walk(root, targetSum, path, paths);
        return paths;
    }

  private:
    void walk(TreeNode *node, int remaining, vector<int> &path, vector<vector<int>> &paths) {
        if (node == nullptr)
            return;
        path.push_back(node->val);
        remaining -= node->val;
        if (node->left == nullptr && node->right == nullptr && remaining == 0) {
            paths.push_back(path);
        }
        walk(node->left, remaining, path, paths);
        walk(node->right, remaining, path, paths);
        path.pop_back();
    }
};

More Binary Trees & BST problems