112. Path Sum
2016-02-04 15:55
363 查看
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
Solution 1
1ms 9.61%
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum (root.left, sum - root.val)
|| hasPathSum(root.right, sum - root.val);
}
}
Solution 2
1ms 9.61%
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return calcSum(root, 0, sum);
}
public boolean calcSum(TreeNode root, int result, int sum){
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return result + root.val == sum;
}
return calcSum(root.left, root.val + result, sum) || calcSum(root.right, root.val + result, sum);
}
}
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.
Solution 1
1ms 9.61%
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum (root.left, sum - root.val)
|| hasPathSum(root.right, sum - root.val);
}
}
Solution 2
1ms 9.61%
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return calcSum(root, 0, sum);
}
public boolean calcSum(TreeNode root, int result, int sum){
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return result + root.val == sum;
}
return calcSum(root.left, root.val + result, sum) || calcSum(root.right, root.val + result, sum);
}
}
相关文章推荐
- 三天学会HTML5——SVG和Canvas的使用
- 简单介绍redis以及ubuntu和windows下怎么安装redis和配置文件详解
- Java回调函数使用
- Python的math模块中的常用数学函数整理
- 为什么java.net.URLEncoder.encode方法要调用两次而不是一次呢?
- 波特率的设置方法
- poj1013 模拟
- Android-Universal-Image-Loader三大组件DisplayImageOptions、ImageLoader、ImageLoaderConfiguration详解
- 安装mongodb副本分片集群
- YZR要补脑!
- 从头认识Spring-1.15 对SpEl的值的操作(2)-对比值
- 详解 Redis 应用场景及应用实例
- 散列的数组
- 比pullTorefresh更好看的下拉刷新
- js监听页面的scroll事件,当移到底部时触发事件
- 删除数据库
- 对称加密,API加密
- JS对象的构建
- USACO Broken Necklace 解题日志
- 使用AutoLayOut的注意事项