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
- 0 ≤ number of nodes ≤ 5000
- -1000 ≤ Node.val, targetSum ≤ 1000
Edge cases to test
- No matching path:
[] - Negative values (can’t prune early)
- Several matching leaves
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
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)