112. Path Sum
2016-07-06 16:50
330 查看
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. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; int tmp = sum - root->val; if(tmp == 0 && !root->left && !root->right) return true; else return hasPathSum(root->left,tmp)||hasPathSum(root->right,tmp); } };
相关文章推荐
- webuploader文件接收服务端
- solution Of 1018. Public Bike Management (30)
- [书目20160706]成功销售实用经典10步骤(美国培训与发展协会实用经典10步系列)
- python vs ruby
- android_结构
- 阿里面经之解答 by cmershen(4)——线程池
- nginx如何防止ddos***
- 《UNIX环境高级编程》---1.UNIX基础知识
- 直播平台的高并发架构设计3.3-播放器端
- 简单掌握桶排序算法及C++版的代码实现
- 数字转换成指定格式的字符串
- (一)MVC5干货篇,目录和路由
- python setup.py用法
- 分分钟学会【A星寻路】~~~~~~~【无上天君与梦瑶的传说】
- Android 关机(reboot)流程 -- "sys.powerctl"
- 在cisco路由器上使用TFTP备份/恢复交换路由的IOS文件
- service 后台下载
- section 1.4 milk3
- 分析数字自动翻滚的动画---加深对属性动画的理解
- 华为机试题--13.求int型数据在内存中存储时1的个数