Algo-Sim › Binary Trees & BST
Path Sum III
Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Prefix sums along the root-to-node path in a hash map: each node counts the earlier prefixes equal to sum − target, and removes its own on the way back.
Problem
Given the root of a binary tree and targetSum, count the paths whose values add up to targetSum. A path may start and end at any nodes, but must go downward, from parent to child.
Constraints
- 0 ≤ number of nodes ≤ 1000
- -10⁹ ≤ Node.val ≤ 10⁹
- -1000 ≤ targetSum ≤ 1000
Edge cases to test
- target 0 with zero values
- Negative values
- A single node equal to the target
Follow-up questions
- Why remove the prefix on the way back up?
- Only prefixes on the current root-to-node path are valid starts; leaving them in would count paths that jump between branches.
- What is the brute force?
- Start a downward DFS from every node: O(n·h), O(n²) on a chain.
Solution
Java
public int pathSum(TreeNode root, int targetSum) {
Map<Long, Integer> seen = new HashMap<>();
seen.put(0L, 1); // the empty prefix above the root
return count(root, 0, targetSum, seen);
}
private int count(TreeNode node, long sum, int target, Map<Long, Integer> seen) {
if (node == null) return 0;
sum += node.val;
int paths = seen.getOrDefault(sum - target, 0);
seen.merge(sum, 1, Integer::sum);
paths += count(node.left, sum, target, seen);
paths += count(node.right, sum, target, seen);
seen.merge(sum, -1, Integer::sum);
return paths;
}Python
def path_sum(root, target_sum):
seen = {0: 1} # the empty prefix above the root
return count(root, 0, target_sum, seen)
def count(node, total, target, seen):
if not node:
return 0
total += node.val
paths = seen.get(total - target, 0)
seen[total] = seen.get(total, 0) + 1
paths += count(node.left, total, target, seen)
paths += count(node.right, total, target, seen)
seen[total] -= 1
return pathsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int pathSum(TreeNode *root, int targetSum) {
unordered_map<long long, int> seen;
seen[0] = 1;
return count(root, 0, targetSum, seen);
}
private:
int count(TreeNode *node, long long sum, int target, unordered_map<long long, int> &seen) {
if (node == nullptr)
return 0;
sum += node->val;
int paths = seen.count(sum - target) ? seen[sum - target] : 0;
seen[sum]++;
paths += count(node->left, sum, target, seen);
paths += count(node->right, sum, target, seen);
seen[sum]--;
return paths;
}
};
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 II (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)