Run time error . help


  • 0
    V
    void connect(struct TreeLinkNode *root) {
    if(root->left==NULL||root->right==NULL)
    {
        if(!root->next)
        root->next=NULL;
        return;
    }
        else
        {
        root->left->next=root->right;
        if(root->next)
        root->right->next=root->next->left;
        else
        root->right=NULL;
        connect(root->left);
        connect(root->right);
        }
    }

  • 0
    S

    Please find below my 8ms solution in C :

    // Initially, all next pointers are set to NULL.
    void contect_Right_Pointer(struct TreeLinkNode *Lnode, struct TreeLinkNode Rnode,struct TreeLinkNode Pnode){

    if(Lnode==NULL)
        return;
    if(Rnode==NULL)
        return;
    
    if(Lnode && Pnode!=NULL)
        Lnode->next=Pnode->right;
    if(Rnode && Pnode!=NULL && Pnode->next!=NULL)
        Rnode->next=Pnode->next->left;
    
     contect_Right_Pointer(Lnode->left,Lnode->right,Lnode);
     contect_Right_Pointer(Rnode->left,Rnode->right ,Rnode);
    

    }

    void connect(struct TreeLinkNode *root) {

    if(root==NULL)
    return ;
    contect_Right_Pointer(root->left,root->right, root);
    }

    LINk https://leetcode.com/discuss/38076/runtime-8ms-in-c


  • 2
    R

    I went through your code. I liked the logic, though it has a few minor issues/typos. I am a Java developer and have little knowledge of C or C++. I am just analyzing your logic here. My apologies, if any of my comments are applicable only to Java.

    1. There is no null check on the node. You get the run time exception when root==null. So, Adding it at the top will prevent your code from throwing a runtime error.

        if(root->next)
            root->right->next=root->next->left;
            else
            root->right=NULL;
    

    In the last line of the above block, you are supposed to set root->right->next to null, not root.right. So, it should be

    if(root->next)
        root->right->next=root->next->left;
        else
        root->right->next=NULL;
    

    I made these two changes to your solution. And it was ran successfully in 8 ms! Congratulations.

    I removed some redundant code from the solution. Here is the final solution.

    void connect(struct TreeLinkNode *root) {
        if(root && root->left && root->right) {
            root->left->next=root->right;
            if(root->next)
                root->right->next=root->next->left;
            else
                root->right->next=NULL;
            connect(root->left);
            connect(root->right);
        }
    }
    

  • 0
    V

    Thanks a lot !


Log in to reply
 

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