资讯专栏INFORMATION COLUMN

leetcode113. Path Sum II

Eirunye / 955人阅读

摘要:题目要求从树中找到所有符合条件的从根节点到叶节点路径,条件即为树上所有节点值的和等于目标值。可以参考这篇博客思路和代码其实这里本质上的思路并没有改变,还是采用深度优先算法,采用自顶向下递归的方式将符合条件的结果放入结果集中。

题目要求
Given a binary tree and a sum, find all root-to-leaf paths where each path"s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / 
            4   8
           /   / 
          11  13  4
         /      / 
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]

从树中找到所有符合条件的从根节点到叶节点路径,条件即为树上所有节点值的和等于目标值。
Path Sum I可以参考这篇博客

思路和代码

其实这里本质上的思路并没有改变,还是采用深度优先算法,采用自顶向下递归的方式将符合条件的结果放入结果集中。

    public List> pathSum(TreeNode root, int sum) {
        List> result = new ArrayList>();
        pathSum(root, sum, new ArrayList(), result);
        return result;
    }
    
    public void pathSum(TreeNode root, int sum, List path, List> result){
        if(root==null) return;
        sum -= root.val;
        if(isLeaf(root) && sum==0){
            path.add(root.val);
            result.add(new ArrayList(path));
            path.remove(path.size()-1);
            return;
        }
        path.add(root.val);
        pathSum(root.left, sum, path, result);
        pathSum(root.right, sum, path, result);
        path.remove(path.size()-1);
        
        
    }
    
    private boolean isLeaf(TreeNode node){
        return node!=null && node.left==null && node.right==null;
    }


想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67384.html

相关文章

  • [LeetCode] Path Sum (I & II & III)

    摘要: 112. Path Sum Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node...

    张金宝 评论0 收藏0
  • [Leetcode-Tree] Path Sum I II III

    摘要:解题思路利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回每次访问一个节点,就将该节点的作为新的进行下一层的判断。代码解题思路本题的不同点是可以不从开始,不到结束。代码当前节点开始当前节点左节点开始当前节点右节点开始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...

    notebin 评论0 收藏0
  • [Leetcode] Path Sum I & II & III 路径和1,2,3

    摘要:只要我们能够有一个以某一中间路径和为的哈希表,就可以随时判断某一节点能否和之前路径相加成为目标值。 最新更新请见:https://yanjia.me/zh/2019/01/... Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addin...

    caiyongji 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<