给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处
。
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
LinkedList<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();//用来存放路径
public List<List<Integer>> pathSum(TreeNode root, int sum) {
recur(root,sum);
return res;
}
void recur(TreeNode root ,int target){
//用来初始化两个链表
if(root==null){
return;
}
path.add(root.val);
target-=root.val;
if(target==0&&root.left==null&&root.right==null){
res.add(new LinkedList(path));
}
//开始递归则遍历二叉树
recur(root.left,target);
recur(root.right,target);
path.removeLast();//重置path链表
}
}