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);
}

最新文章

  1. 使用KRPano资源分析工具分析动态网站资源
  2. Android之debug---menu的getActionView()return null
  3. 老话题:自己编写只截窗口客户区的截屏软件(VB2010)
  4. ORACLE 查看锁
  5. Makefile使用总结
  6. 线段树(维护最大值):HDU Billboard
  7. Swagger 生成 ASP.NET Web API
  8. 分享在MVC3.0中使用jQuery DataTable 插件
  9. temp-内外网同时上的例子
  10. jvm内存分配和回收策略
  11. .NET Core+MySql+Nginx 容器化部署
  12. RPC vs RESTful
  13. UIEvent&amp;nbsp;UIResponder&amp;nbsp;UI_04
  14. Mysql 时间差(年、月、天、时、分、秒)
  15. java 将保单数据 生成图片
  16. JN_0005:PS改变图片指定内容颜色
  17. 【转载】阿里云服务器为网站选配Https证书
  18. Linux记录-shell获取hdfs表查询mysql
  19. django form 组件插件
  20. VS2015 工具箱 保存位置

热门文章

  1. 关于解决Oracle登录:ora-12154:tns:无法解析指定的连接标识符
  2. 深入理解linux网络技术内幕读书笔记(八)--设备注册与初始化
  3. Java中4种权限的理解
  4. 为什么要使用Nginx?
  5. c++应用程序文件的编译过程
  6. (ubuntu)在andorid andk工程中使用ccache加速编译速度
  7. hdu 4605-Magic Ball Game(树状数组)
  8. mysql中DES加密解密
  9. linux修改主机名-IP
  10. 关于ubuntu中的软件安装