leetcode_113_路径总和 II@@dfs

在这里插入图片描述

class Solution {
   
    int sum;
    int tempSum=0;
    boolean flag;
    List<List<Integer>> list=new ArrayList<>();
    List<Integer> tempList=new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root==null ) return new ArrayList<>();
        this.sum=sum;
        dfs(root);
        return list;
    }

    public void dfs(TreeNode root){
        if(root==null) return ;
        if(root.left==null&&root.right==null){
            if((tempSum+root.val)==sum ){
                 tempList.add(root.val);
                list.add(new ArrayList<Integer>(tempList));
                 tempList.remove(tempList.size()-1);
            }
            return ;
        }
        tempSum+=root.val;
        tempList.add(root.val);
        dfs(root.left);
        dfs(root.right);
          tempSum-=root.val;
        tempList.remove(tempList.size()-1);
    }
}

猜你喜欢

转载自blog.csdn.net/ruochen82155551/article/details/107622211