Leetcode--Path Sum
2014-03-20 19:31
267 查看
Problem Description:
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
is 22.
分析:利用递归的思想,一旦出现结果就返回。
代码如下:
/**
* Definition for binary tree
* 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) {
bool left=false,right=false;
if(!root) return false;
if(!root->left&&!root->right&&root->val==sum)
return true;
else
{
left=hasPathSum(root->left,sum-root->val);
right=hasPathSum(root->right,sum-root->val);
if(left||right)
return true;
else
return false;
}
}
};
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.
分析:利用递归的思想,一旦出现结果就返回。
代码如下:
/**
* Definition for binary tree
* 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) {
bool left=false,right=false;
if(!root) return false;
if(!root->left&&!root->right&&root->val==sum)
return true;
else
{
left=hasPathSum(root->left,sum-root->val);
right=hasPathSum(root->right,sum-root->val);
if(left||right)
return true;
else
return false;
}
}
};
相关文章推荐
- 实训五(第二题)
- java获取当前项目路径
- 组合模式
- 域名访问总是session失效
- 关于python函数参数
- 四.4数组做数据成员
- C语言答疑解惑
- Java相对路径读取文件
- 第四周上级项目--三角形类
- rt-thread1.2.0 编译出现..\..\src\kservice.c(787): error: #929: incorrect use of va_arg
- 如何编译m3u8_segmenter
- 傅立叶变换的原理、意义以及如何用Matlab实现快速傅立叶变换
- cocos2d-x内存管理
- 第2章 从资源到机会,规划产品蓝图
- 乱谈数学--傅里叶变换(级数)的原理(一)
- 黑马程序员_C语言的extern和static关键字
- POJ --3009
- 这是高手最常用的第一快捷组合键 - imsoft.cnblogs
- 【Mysql行锁】SELECT...FOR UPDATE和SELECT ...LOCK IN SHARE MODE
- struts2零配置