package Recursion;
import java.util.ArrayList;
import java.util.List;
public class PathSum_113 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null) {
return res;
}
List<Integer> list = new ArrayList<>();
recur(root, sum, list);
return res;
}
private void recur(TreeNode root, int sum, List<Integer> list) {
sum -= root.val;
list.add(root.val);
if (root.left != null) {
recur(root.left, sum , list);
list.remove(list.size() - 1);
}
if (root.right != null) {
recur(root.right, sum , list);
list.remove(list.size() - 1);
}
// 递归结束标志
if (root.left == null && root.right == null) {
if (sum == 0) {
res.add(list);
}
return;
}
}
}
113. Path Sum II(递归、深搜)
最新推荐文章于 2022-03-31 13:37:37 发布