L113 Java回溯

/**
 * 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;
    }
}

你可能感兴趣的:(java,深度优先,开发语言)