LeetCode:113 路径总和Ⅱ(dfs)

class Solution {

    public void dfs(List<List<Integer>>res,TreeNode t,int sum,LinkedList<Integer>que){
        if((sum-t.val)==0&&(t.left==null&&t.right==null)){
            que.offer(t.val);
           // System.out.println(que.toString());
            res.add(new LinkedList<>(que));
            return;
        }
        TreeNode m = t;
        que.offer(m.val);
        if(m.left!=null){
            dfs(res,m.left,sum-m.val,que);
            que.pollLast();
        }
        if(m.right!=null){
            dfs(res,m.right,sum-m.val,que);
            que.pollLast();
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root==null){
            return new LinkedList<>();
        }
        
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        LinkedList<Integer> que = new LinkedList<>();
        TreeNode t = root;
        dfs(res,t,sum,que);
        return res;
    }
}

 

posted @ 2020-10-06 09:12  dlooooo  阅读(138)  评论(0编辑  收藏  举报