LeetCode:Path Sum
2016-04-20 14:57
246 查看
题目描写叙述:
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 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->2which sum is 22.
代码:
bool Solution::hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL) return root->val - sum; else return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val); }
相关文章推荐
- 关于Reactor和Proactor的差别
- IOS、Android html5页面输入的表情符号变成了乱码”???“
- 大数据真实电商数据仓库全流程开发详解
- 编译原理—二进制转十进制
- C++STL库中string类的find()和findfirstof()函数比较
- ios开发多线程篇——GCD的常见用法
- WinForm再Panel中添加子窗体问题总结
- 保护你的Web服务器 iptables防火墙脚本全解读
- 在我开始自由职业生涯前应该明白的4件事
- munmap()函数:解除内存映射
- UVA_384_Slurpys
- NEC发售可实时处理4K影像的超低延迟编解码器
- 大神分享
- 剑指offer面试题 字符串的排列
- C# VS 快捷键
- 改善技术简历的47条原则
- Permutations
- 《疯狂Java讲义(第3版)》.(李刚)——java命名规则及编码规范
- Photometric stereo 深度图优化
- Windows核心编程:DLL注入和API拦截