leetcode[112]Path Sum

问题:给定二叉树和一个数,判断是否存在叶子结点到根结点路径和等于给的数

输入:TreeNode* root, int sum

输出:true/false

思路:分不同情况递归。

wrong answer case [] 0,下面的代码output true,Expected 为false。

代码段 小部件

进行改进。加入判断后,又WA了。

[1,2]   1             Output true             Expected false

发现是犯了111的毛病,没考虑是否是叶子结点。 

画个二叉树,分析一下,继续改进。没一下子把所有情况考虑周到,改了两三次,最后才ac。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
bool cmp(int a)
{
    if(a==0)
        return true;
    else
        return false;
}
class Solution {
public:
    int i=0;    //solve question about blank tree.
    bool hasPathSum(TreeNode* root, int sum) {
        if(i==0&&root==NULL)
        {
            return false;
        }
        if(root==NULL)
        {
            return cmp(sum); 
        }
        else if((root->left==NULL)&&(root->right==NULL))
        {
            i++;
            return cmp(sum-root->val);
        }
        else if(root->right==NULL)
        {
            i++;
            return hasPathSum(root->left, sum-root->val);
        }
        else if(root->left==NULL)
        {
            i++;
            return hasPathSum(root->right, sum-root->val);
        }
        else
        {
            i++;
            return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);;
        }
    }
};

时间复杂度比较高。

隔壁大神code分享[1]

bool hasPathSum(TreeNode *root, int sum) {
        if (root == NULL) 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);
    }
  1. https://leetcode.com/problems/path-sum/discuss/36367/3-lines-of-c%2B%2B-solution
发布了56 篇原创文章 · 获赞 10 · 访问量 6837

猜你喜欢

转载自blog.csdn.net/qq_22148493/article/details/88082054