Leetcode 112. Path Sum
2016-03-28 20:09
483 查看
Question
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,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Code
public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null && sum == root.val) { return true; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); }
相关文章推荐
- POJ 2752 Seek the Name, Seek the Fame(next数组的应用)
- 第五周项目3时间类(1)
- 架构师必看 京东咚咚架构演进
- IO流
- 关于Swift中出现dyld: Library not loaded: @rpath/libswiftCore.dylib错误的解决方法
- LAMP环境配置初体验
- 第5周-项目3-时间类(2)
- laserscan_multi_merger代码解析
- Android面试:谈谈Android的优点和不足之处.
- JavaScript闭包
- 微信开发者模式和新浪SAE之间 Token总是验证失败
- ElasticSearch怎样加入,检索数据
- 30分钟学正则
- Android问题集锦之四十七: Error:Execution failed for task ':app:packageRelease'. > Unable to compute hash of
- 【全排列 - 递归】
- 时间类1
- 输出特殊符号,可以用单引号'引文':echo 'Hello World !'
- BestCoder Round #77 (div.2)
- BZOJ 4401(块的计数-树的划分)
- Android数据解析之XML篇