找出二叉树中满足某种条件的所有路径

其实这篇博客应该说是转载的,
代码复制自:
http://www.nowcoder.com/profile/927826

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

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

public class Solution {
    private ArrayList> listAll = new ArrayList>();
    private ArrayList list = new ArrayList();
    public ArrayList> 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(list));
        FindPath(root.left, target);
        FindPath(root.right, target);
        list.remove(list.size()-1);
        return listAll;
    }
}
我没有发现谁的代码,比他的更短小精致

你可能感兴趣的:(面试&算法)