Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
- Time: O(N)
- Space: O(1)
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null && root.val == sum) {
return true;
}
return hasPathSum(root.left, sum - root.val)
|| hasPathSum(root.right, sum - root.val);
}
Path Sum II
return [ [5,4,11,2], [5,8,4,5] ]
- Time: O(N)
- Space: O(1)
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<>();
pathSumRe(ret, new ArrayList<Integer>(), root, sum);
return ret;
}
private void pathSumRe(List<List<Integer>> ret, List<Integer> path, TreeNode node, int sum) {
if (node == null) {
return;
}
path.add(node.val);
if (node.left == null && node.right == null && node.val == sum) {
ret.add(new ArrayList<>(path));
}
pathSumRe(ret, path, node.left, sum - node.val);
pathSumRe(ret, path, node.right, sum - node.val);
path.remove(path.size() - 1);
}