leetcode——112——Path Sum
2016-04-03 11:53
323 查看
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
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 == NULL) return false; else if (root->left == NULL && root->right == NULL && root->val == sum) return true; else { return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum - root->val); } } };
相关文章推荐
- 软件安装与仿真设置 -- 慕司板IAP15
- android6.0以后删除HttpClient的解决方法
- Android-Studio-插件小结
- 正宗快排
- 对称加密之AES加密
- 支持向量机SVM(五)
- 2016年网易春招软件测试实习生面试
- [转] 记住这14条 关键时刻可以救命!学着保护好自己!
- memset函数
- web进修之—Hibernate 继承映射(5)
- 支持向量机SVM(四)
- Python Discuz 7.2 faq.php 注入漏洞全自动利用工具
- jquery uploadify在IE上传报406HttpError
- NumPy学习笔记
- sublime中输入法输入框只能在一个位置
- Otto使用记录
- 支持向量机SVM(三)
- 解析XML:DOM,SAX,PULL
- iOS开发总结之项目开发中使用UITableView几百行代码搞定级联表格
- pandas学习笔记