leetCode:Path Sum
来源:互联网 发布:dfu刷机会清空数据吗 编辑:程序博客网 时间:2024/06/01 08:47
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.
#include<iostream>using namespace std;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,int theNumber){ if(root==NULL) return theNumber==sum; if(root->left==NULL && root->right==NULL) return theNumber==sum+root->val; sum+=root->val; return (hasPathSum(root->left,sum,theNumber) || hasPathSum(root->right,sum,theNumber)); } bool hasPathSum_version2(TreeNode *root,int sum){ if(root==NULL) return false; if(root->left==NULL && root->right==NULL) return sum==root->val; return hasPathSum_version2(root->left,sum-(root->val)) || hasPathSum_version2(root->right,sum-(root->val)); }};int main() { TreeNode a(5); TreeNode b(4); TreeNode c(8); TreeNode d(11); TreeNode e(13); TreeNode f(4); TreeNode g(7); TreeNode h(2); TreeNode i(1); a.left=&b;a.right=&c; b.left=&d;b.right=NULL; c.left=&e;c.right=&f; d.left=&g;d.right=&h; e.left=NULL;e.right=NULL; f.left=NULL;f.right=&i; g.left=NULL;g.right=NULL; h.left=NULL;h.right=NULL; i.left=NULL;i.right=NULL; Solution sol;// bool hehe=sol.hasPathSum_version2(&a,22); bool hehe=sol.hasPathSum(&a,0,22); cout<<hehe<<endl; }
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
- BMP转成C语言数组文件工具(用image2lcd代替bmp2h.exe)
- 通过借用构造函数解决超类型构造函数传参
- 【leetcode】Remove Duplicates from Sorted List II-很精简
- JavaScript排序算法之插入排序
- Tornado
- leetCode:Path Sum
- 大数据与信息隐私
- 黑马程序员——继承、final关键字、抽象类
- 关于Linux系统性能瓶颈定位分析(一),Nginx状态页测试
- (八)写文档的一些感想
- 编程批量添加区域名称(树形结构表)
- 关于Linux系统指令 top 之 %si 占用高,分析实例一
- 《C和指针》经典入门程序
- android shape资源