AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
小轩喵灬
,
2025-01-13 15:52:32
,
所有人可见
,
阅读 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> findPath(TreeNode root, int sum) {
dfs(root, sum, new ArrayList<>());
return res;
}
private void dfs(TreeNode node , int target , List<Integer> path) {
if (node == null) {
return;
}
path.add(node.val);
target -= node.val;
if (target == 0 && node.left == null && node.right == null) {
res.add(new ArrayList<>(path));
} else {
dfs(node.left, target, path);
dfs(node.right, target, path);
}
path.remove(path.size() - 1);
}
}