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
原创粉丝点击