剑指offer:二叉树中和位某一值的路径

阅读 44

2022-03-11

在这里插入图片描述

class Solution {

    List<List<Integer>> list1;
    List<Integer> list2;
    
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        list1=new LinkedList<List<Integer>>();
        list2=new LinkedList<>();
        dfs(root,target);
        return list1;
    }
    void dfs(TreeNode root,int target){
        if(root==null) return;
        list2.add(root.val);
        if(target-root.val==0&&(root.right==null&&root.left==null)){
            list1.add(new LinkedList(list2)); 
        }
        dfs(root.left,target-root.val);
        dfs(root.right,target-root.val);
        list2.remove(list2.size()-1);
    }

}

精彩评论(0)

0 0 举报