输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
剑指 Offer 34. 二叉树中和为某一值的路径 - 力扣(LeetCode) (leetcode-cn.com)
思路:要找所有路径,所以要回溯。
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int target) {
path(0, target, root);
return res;
}
List<List<Integer>> res = new LinkedList(); //存储所有路径
LinkedList<Integer> list = new LinkedList(); //存储到某个节点的路径
public void path(int count, int target, TreeNode node){
if(node == null){
return;
}
list.add(node.val);
if(count + node.val == target){
if(node.left == null && node.right == null){ //判断叶节点
res.add(new LinkedList<Integer>(list));
}
}
path(count + node.val, target, node.left); //递归左子树
path(count + node.val, target, node.right); //递归右子树
list.removeLast(); //回溯,要把当前节点从路径中删除
}
}