leetcode_question_112 Path Sum
2024-10-13 14:15:18
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->2
which sum is 22.
DFS:
bool findPathSum(TreeNode* root, vector<int> &path, int sum)
{
path.push_back(root->val);
if(root->left == NULL && root->right == NULL){
vector<int>::iterator it = path.begin();
int tmpsum = 0;
for(; it != path.end(); ++it)
tmpsum += *it;
path.pop_back();
if(tmpsum == sum)
return true;
else
return false;
}
bool flag = false;
if(root->left)
flag = findPathSum(root->left,path,sum);
if(!flag && root->right)
flag = findPathSum(root->right,path,sum);
path.pop_back();
return flag;
}
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)
return false;
vector<int> path;
return findPathSum(root, path,sum);
}
最新文章
- 使用KRPano资源分析工具分析动态网站资源
- Android之debug---menu的getActionView()return null
- 老话题:自己编写只截窗口客户区的截屏软件(VB2010)
- ORACLE 查看锁
- Makefile使用总结
- 线段树(维护最大值):HDU Billboard
- Swagger 生成 ASP.NET Web API
- 分享在MVC3.0中使用jQuery DataTable 插件
- temp-内外网同时上的例子
- jvm内存分配和回收策略
- .NET Core+MySql+Nginx 容器化部署
- RPC vs RESTful
- UIEvent&;nbsp;UIResponder&;nbsp;UI_04
- Mysql 时间差(年、月、天、时、分、秒)
- java 将保单数据 生成图片
- JN_0005:PS改变图片指定内容颜色
- 【转载】阿里云服务器为网站选配Https证书
- Linux记录-shell获取hdfs表查询mysql
- django form 组件插件
- VS2015 工具箱 保存位置