二叉树中和为某一值的路径

来源:互联网 发布:精准扶贫数据平台登录 编辑:程序博客网 时间:2024/06/06 01:41

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。、

路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。


publicclass Solution {
    privateArrayList<ArrayList<Integer>> listAll = newArrayList<ArrayList<Integer>>();
    privateArrayList<Integer> list = newArrayList<Integer>();
    publicArrayList<ArrayList<Integer>> FindPath(TreeNode root,inttarget) {
        if(root == nullreturnlistAll;
        list.add(root.val);
        target -= root.val;
        if(target == 0&& root.left == null&& root.right == null)
            listAll.add(newArrayList<Integer>(list));
        FindPath(root.left, target);
        FindPath(root.right, target);
        list.remove(list.size()-1);
        returnlistAll;
    }
}
我觉得哈,因为add添加的是引用,如果不new一个的话,后面的操作会更改这个list

0 0
原创粉丝点击