You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree – it does not have to start at the root.
To solve this problem, we need to design an algorithm that can find all paths in a binary tree that sum up to a given value. The paths can begin and end at any node in the tree.
DFS Traversal: Use Depth-First Search (DFS) to traverse each node.
Path Tracking: Keep track of the path from the root to the current node.
Subpath Sums: For each node, check all possible subpaths ending at that node to see if they sum up to the given target value.
Backtracking: Ensure that after exploring a node, we backtrack to explore other possible paths.
We do DFS with following cases:
Base case - If the node is null, return.
Path Tracking: Add the current node to the path.
Subpath Sums: Iterate backward through the current path and calculate the sum of subpaths ending at the current node. If any subpath sums up to the target, add it to the result.
Recursive Calls: Recursively explore the left and right subtrees.
Backtracking: Remove the last node from the current path after exploring both subtrees.
publicclassSolution {
public List < List<Integer>>pathSum(TreeNode root, int targetSum) {
List < List<Integer>> ans =new ArrayList<>();
List<Integer> currPath =new ArrayList<>();
dfs(root, sum, currPath, ans);
return ans;
}
privatevoiddfs(TreeNode node, int target, int currSum, List<Integer> currPath, List <List<Integer>> ans) {
if (node ==null) {
return;
}
// Add the current node to the path currPath.add(node.val);
int newSum = currSum + node.val;
if (newSum == target) {
ans.add(new ArrayList<>(currPath));
}
// Recursively search the left and right subtrees dfs(node.left, target, newSum, currPath, ans);
dfs(node.right, target, newSum, currPath, ans);
// Backtrack by removing the current node from the path currPath.remove(currentPath.size() - 1);
}
}
classSolution:
defpathSum(self, root, target):
defdfs(node, current_path):
ifnot node:
return# Add current node to the path current_path.append(node.val)
# Check for valid paths that end at current node running_sum =0for i in range(len(current_path) -1, -1, -1):
running_sum += current_path[i]
if running_sum == target:
result.append(current_path[i:])
# Recur for left and right children dfs(node.left, current_path)
dfs(node.right, current_path)
# Backtrack: remove the current node from the path current_path.pop()
result = []
dfs(root, [])
return result