LeetCode | Path Sum(路径和)
来源:互联网 发布:地图矢量数据 编辑:程序博客网 时间:2024/05/21 08:36
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.
题目解析:
这道题是到达叶节点的和是否等于sum,中间节点达到不行。也不能全部当成正数来判断,正如代码中注释掉的部分if(root->val > sum),有负数出现,就会造成错误判断。唯一的成功的地方是:当root->val == sum && root->left == NULL && root->right == NULL 这三个条件同时满足时返回真。其他情况,继续递归就行,在根指针指向NULL的时候返回假。省去了额外的判断。
class Solution {public: bool hasPathSum(TreeNode *root, int sum) { if(root == NULL){ return false; } /* if(root->val > sum) return false; */ if(root->val == sum && root->left == NULL && root->right == NULL) return true; return hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum-root->val); }};
期间出现的错误:
由于当输入是空的时候,不能仅用
if(root == NULL){ if(sum==0) return true; return false;}
第二种错误,是不能忽略负数的情况。
0 0
- LeetCode | Path Sum(路径和)
- LeetCode 112. Path Sum(路径和)
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- LeetCode | Path Sum II(路径和2)
- LeetCode | Minimum Path Sum(最小路径和)
- LeetCode OJ 之 Path Sum(求路径和)
- LeetCode OJ 之 Path Sum II (路径和 - 二)
- LeetCode OJ 之 Minimum Path Sum (最小路径和)
- LeetCode 64. Minimum Path Sum(最小路径和)
- LeetCode 113. Path Sum II(路径和)
- LeetCode--Minimum Path Sum (最小路径和)Python
- Path Sum 二叉树路径和 @LeetCode
- LeetCode Path Sum II路径和II
- [leetcode]Minimum Path Sum 最小路径和
- Leetcode:Minimum Path Sum 最小路径和
- LeetCode-112-Path Sum(路径和)
- hadoop集群完整配置
- HDU 4946 Area of Mushroom 凸包
- hdu 2051 Bitset(水题)
- HTML5边玩边学(9):俄罗斯方块就是这么简单 之 控制界面篇(源码)
- Java反射机制
- LeetCode | Path Sum(路径和)
- 网站用户行为分析架构指导
- Poj 2029 Get Many Persimmon Trees 二维树状数组
- Android ExpandableListView 使用记录
- php,js RSA加解密密码
- windows7下配置tomcat7的zip版本
- hbase配置文档
- hdu 3714 三分法
- aptana studio 添加jquery提示