给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> list = new LinkedList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
LinkedList<Integer> nlist = new LinkedList<>();
dfs(sum, root, nlist);
return list;
}
public void dfs(int sum, TreeNode root, LinkedList<Integer> nlist){
if(root == null) return ;
//记录经过的节点
nlist.add(root.val);
if(root.left == null && root.right == null && root.val == sum){
list.add(new LinkedList(nlist));
}
dfs(sum - root.val, root.left, nlist);
dfs(sum - root.val, root.right, nlist);
//删除此节点的记录,返回上一节点,继续遍历
nlist.removeLast();
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。