LeetCode OJ 112. Path Sum
2016-04-28 10:32
281 查看
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
return true, as there exist a root-to-leaf path
代码如下:
For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path
5->4->11->2which sum is 22.
代码如下:
/** * 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) { if(root == null) return false; if(root.left==null && root.right==null){ if(root.val==sum) return true; else return false; } boolean left = false; boolean right = false; if(root.left != null){ left = hasPathSum(root.left, sum - root.val); } if(root.right != null){ right = hasPathSum(root.right, sum - root.val); } if(left==true || right==true) return true; else return false; } }
相关文章推荐
- Spring 注解 @Resource和@Autowired
- 使用Cydia Substrate 从Native Hook Android Native世界
- jsp获取请求路径
- jquery 1.9 浏览器判断
- Python 与 网络爬虫
- Android MD控件之CardView
- Ajax实例:原生js+thinkphp+ajax
- 进程和线程学习理解
- CF Educational Round 12, C
- ListView中嵌套GridView,监听事件发生冲突。
- 欢迎使用CSDN-markdown编辑器
- Python 元组
- 判断ListView的第一个/最后一个item是否完全显示
- (转)Android Eclipse 代码混淆
- setInterval最大时间
- iOS-App的启动页设置
- hibernate 数据缓存
- Win7系统开机进入欢迎界面出现黑屏的解决方法
- PHP安装配置及解决方案
- Hive 查询中的分组排名