题解 | #二叉树中和为某一值的路径(二)#

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

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    LinkedList<Integer> path = new LinkedList<>();
    ArrayList<ArrayList<Integer>> result = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        //递归应该能解决吧
         dfs(root,expectNumber);
        return result;
    }
    void dfs(TreeNode root, int target){
        if(root == null){
            return;
        }
        path.add(root.val);
        target -= root.val;
        
        if(target == 0 && root.left == null && root.right == null){
            result.add(new ArrayList<>(path));
        }
        //如果仅仅是为 0 还是需要回溯 或者找其他左 右数递归
        dfs(root.left, target);
        dfs(root.right, target);
        path.removeLast();
    }
}
全部评论

相关推荐

03-24 12:55
已编辑
榆林学院 软件测试
点赞 评论 收藏
分享
高斯林的信徒:问你有没有保底,好人啊,就差把这是kpi面告诉你了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务