LeetCode LCR 153. 二叉树中和为目标值的路径(DFS)
原题链接
中等
作者:
autumn_0
,
2024-09-27 08:06:41
,
所有人可见
,
阅读 2
/**
* Definition for a binary tree node.
* 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>> pathTarget(TreeNode root, int target){
recur(root, target);
return res;
}
void recur(TreeNode root, int tar){
if(root == null) return ;
path.add(root.val);
tar -= root.val;
if(tar == 0 && root.left == null && root.right == null)
res.add(new LinkedList(path));
recur(root.left, tar);
recur(root.right, tar);
path.removeLast();
}
}