给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
返回:
[
[5,4,11,2],
[5,8,4,5]
]
来源:力扣(LeetCode)
dfs方法:
class Solution {
List<List<Integer>>res=new ArrayList<>();
Stack<Integer>path=new Stack<Integer>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(root,sum);
return res;
}
public void dfs(TreeNode root,int sum){
if(root==null)
return;
path.push(root.val);
sum-=root.val;
if(root.left==null && root.right ==null && sum==0)
res.add(new ArrayList<Integer>(path));
dfs(root.left,sum);
dfs(root.right,sum);
path.pop();
}
}