What is wrong with my C code ?


  • 0
    V
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    bool isBalanced(struct TreeNode* root) {
        int lheight;
        int rheight;
        if (root==NULL);
        return 1;
        lheight = height(root->left);
        rheight = height(root->right);
        if ( abs(lheight-rheight)<=1 && isBalanced(root->left) && isBalanced(root->right) )
        return 1;
        return 0;
    }
    
    int height(struct Treenode* root)
    {
        if (root==NULL);
        return 0;
        else
        {
            int lDepth=height(root->left);
        int rDepth=height(root->right);
        if (lDepth>rDepth)
        return(lDepth+1);
        else return(rDepth+1);
    }
    }

  • 0
    A

    Firstly, remove the semicolon at the end of this if if (root==NULL);

    That makes your 'if' clause bodyless and you will always be returned true.


  • 0
    V

    Thanks, I have removed the semicolon. Now a compile error is showing up which says :
    'warning: implicit declaration of function ‘height’ [-Wimplicit-function-declaration]'


  • 0
    A

    That's because you don't have a function declaration on top ( before isBalanced() ) for height(). Either put up a declaration on top or you can bring the whole definition up there as well.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.