List<List<Integer>> out = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null) {
return out;
}
dfs(root, sum, new LinkedList<>());
return out;
}
public void dfs(TreeNode root, int sum, LinkedList<Integer> res) {
if (root == null) return;
res.add(root.val);
sum -= root.val;
if (sum == 0 && (root.left == null && root.right == null)) {
out.add(new LinkedList<>(res));
}
dfs(root.left, sum, res);
dfs(root.right, sum, res);
res.removeLast();
}
二叉树中和为某一值的路径
最新推荐文章于 2024-02-18 10:47:26 发布