Path Sum
2015-12-09 09:34
127 查看
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
sum is 22.
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) { return sumCount(root, sum, 0); } bool sumCount(TreeNode* node, int sum, int curSum){ if(node == NULL) return false; if(node->left == NULL && node->right == NULL){ return (curSum + node->val) == sum; }else{ return sumCount(node->left, sum, curSum + node->val) || sumCount(node->right, sum, curSum + node->val); } } };
相关文章推荐
- C#中string类型前加@标志的作用
- 夺命雷公狗---javascript NO:07 事件编程介绍
- OpenCL
- ImageSlider使用体会
- VS2012编译luabind
- qemu-system-x86_64: drive with bus=0, unit=0 (index=0) exists 错误原因
- Bresenham算法
- 性能优化-转载篇
- 自定义鼠标选中样式
- 夺命雷公狗---javascript NO:06 数组定义和遍历
- js获取鼠标位置实例详解
- 分享几篇有关react-native的博客
- Percona Toolkit包安装
- PE总结9 --PE文件结构之 解析导出表
- 【java基础】java反射机制
- 黑马程序员——C语言——typedef和#define
- android 6.0 adb 编译
- Android开发调节屏幕亮度
- rpm 安装mysql
- 分享几篇有关react-native的博客