ntree.aiPath Sum
Solutions
1. Depth First Search
O(n·h) time | O(h²) space, for a tree of height h
Intuition
We can traverse through the tree with DFS, keeping the path from the root to each node.
At each step we traverse backwards checking how many parents form a path with the current node which adds up to the target.
Algorithm
- Create a
dfsfunction taking a node, a path to this node and a target.- Return
0when the node is null. - Create
countandsuminteger variables. - Add the node's value to the path.
- Iterate through the path from the last element to the first element, adding the element's value to
sumand increasingcountifsumis equal totarget. - Call
dfswith the left child and the right child, add their results tocountand return it.
- Return
- Call
dfswith the root node, empty path and target.
target = 3
3
2
1
-1
forward: node = 3, 3 == 3, count
1 / 9
target = 3
3
2
1
-1
Code
Code
def pathSum(root: BinaryTreeNode, target: int) -> int:
return dfs(root, [], target)
def dfs(node: BinaryTreeNode, path: list[int], target: int) -> int:
if not node:
return 0
count = sum = 0
path = path + [node.val]
for value in reversed(path):
sum += value
if sum == target:
count += 1
return (count
+ dfs(node.left, path, target)
+ dfs(node.right, path, target))
/**
* @param {BinaryTreeNode} root
* @param {number} target
* @returns {number}
*/
var pathSum = function (root, target) {
return dfs(root, [], target)
}
function dfs(node, path, target) {
if (!node) return 0
let count = 0, sum = 0
path = [...path, node.val]
for (let i = path.length - 1; i >= 0; i--) {
sum += path[i]
if (sum === target) count += 1
}
return count + dfs(node.left, path, target) + dfs(node.right, path, target)
}
import java.util.Arrays;
class Solution {
public int pathSum(BinaryTreeNode root, int target) {
return dfs(root, new int[0], target);
}
private int dfs(BinaryTreeNode node, int[] path, int target) {
if (node == null) return 0;
int count = 0;
long sum = 0;
path = Arrays.copyOf(path, path.length + 1);
path[path.length - 1] = node.val;
for (int i = path.length - 1; i >= 0; i--) {
sum += path[i];
if (sum == target) count += 1;
}
return count
+ dfs(node.left, path, target)
+ dfs(node.right, path, target);
}
}
2. Prefix Sums and Hash Table
O(n) time | O(n) space
Intuition
We can traverse through the tree with DFS, keeping the path from the root to each node and the sums to those nodes in a hash table.
At each step, the number of parents with sums equal to the current sum minus target is the number of paths ending at this node that add up to the target.
Algorithm
- Create a hash map and put the value
1for sum0. - Create a
dfsfunction taking a node, the hash map,sumand a target.- Return
0when the node is null. - Add the node's value to
sum. - Create
countvariable with the value in the hash map at keysum - target. - Increase the value by one for the key
sumin the hash map. - Increase
countbydfscalled with the left node and bydfscalled with the right node. - Decrease the value in the hash map at key
sumby one. - Return
count.
- Return
- Call
dfswith the root node, the hash map,0and the target.
target = 3
3
2
1
-1
0→1
node = 3, sum = 3, 3 - 3 = 0, 0 is in the hash map once, count
1 / 5
target = 3
3
2
1
-1
0→1
3→1
5→1
6→1
2→1
Code
Code
def pathSum(root: BinaryTreeNode, target: int) -> int:
return dfs(root, {0: 1}, 0, target)
def dfs(node: BinaryTreeNode, sums: dict[int, int], sum: int, target: int) -> int:
if not node:
return 0
sum += node.val
count = sums.get(sum - target, 0)
sums[sum] = sums.get(sum, 0) + 1
count += dfs(node.left, sums, sum, target)
count += dfs(node.right, sums, sum, target)
sums[sum] -= 1
return count
/**
* @param {BinaryTreeNode} root
* @param {number} target
* @returns {number}
*/
var pathSum = function (root, target) {
return dfs(root, new Map([[0, 1]]), 0, target)
}
function dfs(node, sums, sum, target) {
if (!node) return 0
sum += node.val
let count = sums.get(sum - target) || 0
sums.set(sum, (sums.get(sum) || 0) + 1)
count += dfs(node.left, sums, sum, target)
count += dfs(node.right, sums, sum, target)
sums.set(sum, sums.get(sum) - 1)
return count
}
import java.util.HashMap;
import java.util.Map;
class Solution {
public int pathSum(BinaryTreeNode root, int target) {
Map<Long, Integer> sums = new HashMap<>();
sums.put(0L, 1);
return dfs(root, sums, 0, target);
}
private int dfs(BinaryTreeNode node, Map<Long, Integer> sums, long sum, int target) {
if (node == null) return 0;
sum += node.val;
int count = sums.getOrDefault(sum - target, 0);
sums.put(sum, sums.getOrDefault(sum, 0) + 1);
count += dfs(node.left, sums, sum, target);
count += dfs(node.right, sums, sum, target);
sums.put(sum, sums.get(sum) - 1);
return count;
}
}
Was the explanation clear?
# Definitions:# class BinaryTreeNode:# def __init__(self, val=0):# self.val = val# self.left = None# self.right = None def pathSum(root: BinaryTreeNode, target: int) -> int: pass 10
5
3
3
-2
2
1
-3
11
Press Visualise to step through your code.