LeetCode笔记:112. Path Sum
来源:互联网 发布:淘宝达人非卖家账号 编辑:程序博客网 时间:2024/06/08 19:17
问题:
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.
For example:
Given the below binary tree and sum = 22,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
大意:
给出一个二叉树和一个值,判断树是否有从根节点到叶子节点的路径让每个节点的值加起来等于给出的值。
例子:
给出下面的二叉树以及 sum = 22,
返回true,因为存在根节点到叶子节点的路径 5->4->11->2 加起来的和为22。
思路:
这个因为只需要判断有没有路径满足,也就是说只需要找到一条即可,那么采用深度优先遍历比较好,用递归来实现。
每次判断当前路径的累加和是否等于目标值了,如果等于,因为题目要求从根节点到叶子节点,所以还要判断是否已经到叶子节点了,这个对有无左右子节点判断就可以了。
如果还不等于,那么就继续判断走左子节点或者走右子节点有没有等于。
要注意的是题目并没说节点值都是正数,我之前对当前的累加和是否已经大于了目标值来希望减少一些多余的运算,属于自作聪明了,对于负数目标值来说,就完全错误了。
代码(Java):
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean hasPathSum(TreeNode root, int sum) { return canSum(root, sum, 0); } public boolean canSum(TreeNode root, int sum, int nowSum) { if (root == null) return false; nowSum = nowSum + root.val; System.out.println(nowSum); if (nowSum == sum && root.left == null && root.right == null) return true; else return canSum(root.left, sum, nowSum) || canSum(root.right, sum, nowSum); }}
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_
- LeetCode笔记:112. Path Sum
- leetcode笔记:Path Sum
- leetcode笔记-Path Sum
- [leetCode刷题笔记]112. Path Sum
- LeetCode 112. Path Sum
- [LeetCode]112.Path Sum
- 【LeetCode】112.Path Sum
- [Leetcode] 112. Path Sum
- [leetcode] 112.Path Sum
- 112. Path Sum LeetCode
- Leetcode 112. Path Sum
- LeetCode *** 112. Path Sum
- leetcode-112. Path Sum
- Leetcode 112. Path Sum
- 112.[Leetcode]Path Sum
- LeetCode 112. Path Sum
- Leetcode 112. Path Sum
- 【leetcode】112. Path Sum
- java消息队列 ActiveMQ实例
- 动态链接库导入库和静态链接库的区别
- hibernate和spring和struts2工作原理
- Doxygen的安装与配置及简单注释规范
- 仿咸鱼键盘
- LeetCode笔记:112. Path Sum
- angularjs $http调用接口的方式
- Ubuntu16.04 更改普通用户权限<1000:1000改为0:0>后只能guest身份进入系统
- android6.0 缺失HttpClient的相关类的解决方法
- Tensorflow一些常用基本概念与函数(1)
- 存储器
- iOS 环信Demo集成即时聊天和UI
- 用已有的模型来训练自己的数据集(finetune)
- Spring MVC 上传图片保存到本地并立即显示