递归实现:
/**
* 剑指 Offer 34. 二叉树中和为某一值的路径
*
* 执行用时: 1 ms
* 内存消耗: 38.6 MB
*
*/
public class PathSum {
public List<List<Integer>> pathSum(TreeNode root, int target) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
ArrayList<Integer> path = new ArrayList<>();
preOrder(root, target, path, res);
return res;
}
private void preOrder(TreeNode root, int curVal, ArrayList<Integer> path, List<List<Integer>> res) {
if (root == null) return;
path.add(root.val);
curVal -= root.val;
if (root.left == null && root.right == null) {
if (curVal == 0) res.add(new ArrayList<>(path));
}
preOrder(root.left, curVal, path, res);
preOrder(root.right, curVal, path, res);
path.remove(path.size() - 1);
curVal += root.val;
}
}