示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
Deque<Integer> path = new LinkedList<Integer>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(root, sum);
return ret;
}
public void dfs(TreeNode root, int sum) {
if (root == null) {
return;
}
path.offerLast(root.val);
sum -= root.val;
if (root.left == null && root.right == null && sum == 0) {
ret.add(new LinkedList<Integer>(path));
}
dfs(root.left, sum);
dfs(root.right, sum);
path.pollLast();
}
}
路径总和 II
最新推荐文章于 2024-06-26 14:32:15 发布