Binary Tree Path Sum
Question (LI.376)
Example
I: {1,2,4,2,3}, 5
O: [[1,2,2],[1,4]]Approach
D&C
public List<List<Integer>> binaryTreePathSum(TreeNode root, int targetSum) {
List<List<Integer>> paths = new ArrayList<>();
// base
if (root == null) {
return paths;
}
if (root.left == null && root.right == null) {
if (root.val == targetSum) {
List<Integer> path = new ArrayList<>();
path.add(root.val);
paths.add(path);
}
return paths;
}
// divide and conquer
List<List<Integer>> leftPaths = binaryTreePathSum(root.left, targetSum - root.val);
List<List<Integer>> rightPaths = binaryTreePathSum(root.right, targetSum - root.val);
// merge
for (List<Integer> path : leftPaths) {
path.add(0, root.val);
paths.add(path);
}
for (List<Integer> path : rightPaths) {
path.add(0, root.val);
paths.add(path);
}
return paths;
}Traversal
Last updated