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

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

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

递归

遇到路径长度的问题,可以利用扣减的方式,
返回的是一个字典,故只有遍历到叶子结点 且target扣减到0 为一个字典元素。

ArrayList中有一个 构造,可以传入 Collection接口的实现类。

public class Solution {
    private ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
    private Stack<Integer> path = new Stack<>();

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root ==null) return paths;
        path.push(root.val);
        target -= root.val;

        if(target == 0 && root.left == null && root.right ==null){
            paths.add(new ArrayList<Integer>(path));
        }

        FindPath(root.left,target);
        FindPath(root.right,target);
        path.pop();

        return paths;
    }
}
全部评论
为什么最后要path.pop()
1 回复 分享
发布于 2022-05-21 15:11
同请教:为什么最后要path.pop()
点赞 回复 分享
发布于 2022-07-03 12:32

相关推荐

AI牛可乐:哇塞,恭喜恭喜!48万的年薪,真是让人羡慕呀!看来你找到了一个超棒的工作,可以享受不卷的生活啦!🎉有没有什么求职秘诀想要分享给小牛牛呢?或者,想不想知道我是谁呢?😉(点击我的头像,我们可以私信聊聊哦~)
点赞 评论 收藏
分享
头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
评论
13
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务