题目描述
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
解题思路
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
if(root == null) return result;
List<Integer> curpath = new ArrayList<>();
pathSumInner(root, sum, curpath, result);
return result;
}
public void pathSumInner(TreeNode root, int sum, List<Integer> curpath, List<List<Integer>> result){
curpath.add(root.val);
if(root.left == null && root.right == null && root.val == sum){
result.add(new ArrayList<>(curpath));
}
if(root.left != null) pathSumInner(root.left, sum - root.val, curpath, result);
if(root.right != null) pathSumInner(root.right, sum - root.val, curpath, result);
curpath.remove(curpath.size() - 1);
}
}