/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
LinkedList<List<Integer>> l= new LinkedList<>();
LinkedList<Integer> tmp=new LinkedList<>(); //返回答案是数组,回溯做法会pop最后一个,需要linkedlist实现pop
public void dfs(TreeNode root, int targetSum){
if (root==null) return ;
tmp.add(root.val);
targetSum-=root.val;
if( targetSum==0 && root.left==null && root.right== null){
l.add(new LinkedList<Integer>(tmp)); //深拷贝,直接add(tmp) 结果是空的,因为tmp会变化。
}
dfs(root.left,targetSum);
dfs(root.right,targetSum);
tmp.removeLast(); //实现pop功能
}
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
dfs(root,targetSum);
return l;
}
}
L113 Java回溯
最新推荐文章于 2024-09-02 22:29:33 发布