Path Sum (leetcode)
来源:互联网 发布:软件编程自学网站 编辑:程序博客网 时间:2024/05/01 03:24
题目:
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.
题目来源:https://oj.leetcode.com/problems/path-sum/
解题思路:用深搜,即可。#include<iostream>#include<queue>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};bool dfs(TreeNode *root,int temp,int sum){if(root==NULL)return false;if(root->left==NULL && root->right==NULL){if(temp+root->val==sum)return true;else return false;}if(dfs(root->left,temp+root->val,sum))return true;if(dfs(root->right,temp+root->val,sum))return true;return false;} bool hasPathSum(TreeNode *root, int sum) {if(root==NULL && sum!=0)return 0;return dfs(root,0,sum); }int main(){TreeNode *root=new TreeNode(1);root->left=new TreeNode(2);root->right=new TreeNode(3);cout<<hasPathSum(root,5)<<endl;system("pause");return 0;}
0 0
- leetcode Path Sum && Path Sum ||
- 【Leetcode】Path Sum (Sum)
- leetcode:leetcode :Path Sum
- 【Leetcode】Path Sum II (Sum)
- LeetCode: Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- LeetCode Minimum Path Sum
- LeetCode Path Sum
- LeetCode Path Sum II
- [Leetcode] Path Sum
- [Leetcode] Path Sum II
- LeetCode : Minimum Path Sum
- [Leetcode] Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- [LeetCode] Path Sum
- [LeetCode] Path Sum II
- Spring MVC 中使用ajax发送POST请求时的参数问题
- IOS获取系统通讯录使用权限的优雅方式
- iOS带有勾选框的提示框(封装代码)
- Android Launcher分析和修改4——初始化加载数据
- C# Activex开发、打包、签名、发布(转)
- Path Sum (leetcode)
- IOS7 8中tableview分割线缺少15像素
- Android内存使用——垃圾回收LOG,GC_CONCURRENT等的意义的说明(有用)
- AssetBundle杂谈
- CSharp学习视频分享与开发技术QQ交流群
- 第十一周 项目六:回文数
- CocoaPods详解之----制作篇
- quartz 动态添加任务、暂停、删除
- CoreText使用