面试题25:二叉树中和为某一值的路径

来源:互联网 发布:公司数据库 编辑:程序博客网 时间:2024/06/17 20:15
链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
来源:牛客网

public class Solution {    private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();//保存所有路径    private ArrayList<Integer> list = new ArrayList<Integer>();//保存单条路径    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {        if(root == null) return listAll;        list.add(root.val);        target -= root.val;        if(target == 0 && root.left == null && root.right == null)             listAll.add(new ArrayList<Integer>(list));//不重新new的话从始至终listAll中所有引用都指向了同一个一个list        FindPath(root.left, target);        FindPath(root.right, target);        list.remove(list.size()-1);        return listAll;    }}

阅读全文
0 0