思想:dfs暴搜,注意千万别忘记撤销本次做的操作,为了不影响下一轮操作,时间复杂度为O(2^n),空间复杂度为O(2 ^n )
/**
* 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>> res = new ArrayList<>();
public void dfs(TreeNode root,int sum,List<Integer> trace){
//终止条件
if(root==null) return;//注意不能在这里面做下面那个if判断,因为叶子节点的左右孩子均为空,这样会生成两条符合条件的路径
trace.add(root.val);
sum-=root.val;
if(root.left==null&&root.right==null&&sum==0){
res.add(new ArrayList<>(trace));
}
//做本轮选择
dfs(root.left,sum,trace);
dfs(root.right,sum,trace);
//不要忘记取消本轮做的选择,不影响下一轮选择(不要忘记这里)
sum+=root.val;
trace.remove(trace.size()-1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null) return res;
List<Integer> trace = new ArrayList<>();
dfs(root,sum,trace);
return res;
}
}