Leetcode66: Path Sum
2015-09-19 22:13
162 查看
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 dfs(TreeNode* Node, int sum, int cursum) { if(Node == NULL) return false; if(!Node->left && !Node->right) return Node->val+cursum == sum; return dfs(Node->left, sum, cursum+Node->val) || dfs(Node->right, sum, cursum+Node->val); } bool hasPathSum(TreeNode* root, int sum) { return dfs(root, sum, 0); } };
相关文章推荐
- 为什么整个互联网行业都缺前端工程师?
- popupMenu-----弹出菜单
- 屌丝之歌
- mysql学习笔记——远程连接数据库
- win7 bp SetDlgItemText
- Noip2008提高组初赛 C
- 第二次作业(上):个人项目实践
- Lecture2-3Guarantee of PLA
- Leetcode65: Move Zeroes
- ARM学习记录1
- NIO——buffer
- NIO——Channel
- bzoj-2095 Bridges
- Zookeeper linux下使用
- 自己写的轻量级PHP框架trig与laravel5.1,yii2性能对比
- yii rules 验证详解
- MongoDB操作
- Windows Server 2008 R2网站访问PHP响应慢的解决方法
- 黑马程序员-----反射技术
- Mining Massive Datasets课程笔记(一)