BST to DLL Code failing

void help(Node* root, Node* &head){
    if(!root)   return;
    
    Node *left = root->left, *right = root->right;
    help(left,head);
    
    if(!pre){
        pre = root;
        head = root;
    }else{
        root->left = pre;
        pre->right = root;
    }
    root->right = head;
    head->left = root;
    pre = root;
    help(right,head);
    return;
}

Node *bTreeToCList(Node *root)
{
    if(!root)   return root;
    Node* head = NULL;
    help(root,head);
    return head;
}

This code is failing on some test cases. Please explain y.

hey @Hyperian are you failing 3,4 & 5 test case number?

Try Submitting this code

void help(Node* root, Node* &head){
    if(root == NULL)   return;
    
    Node *left = root->left, *right = root->right;
    help(left,head);
    
    if(!pre){
       // pre = root;
        head = root;
    }else{
        root->left = pre;
        pre->right = root;
    }
    /*root->right = head;
    head->left = root;
    */
    pre = root;
    help(right,head);
}

Node *bTreeToCList(Node *root)
{
    if(root == NULL)   return NULL;
    Node* head = NULL;
    help(root,head);
    return head;
}

this was for simple bst to dll, ya commented out line were for circular dll. I trieed this code over gfg but failed there, dont know why. Showing error on submission case even though the case passes it run in a custom input.

Share the link where you are submitting this code.

https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1

Your logic was correct just some issue with the implementation which i have resolved here

Node* help(Node* root, Node* &pre){
    if(root == NULL)   return root;
    Node* head = help(root->left, pre);
    
    if(!pre){
       // pre = root;
        head = root;
    }else{
        pre->right = root;
        root->left = pre;
    }
    /*root->right = head;
    head->left = root;
    */
    pre = root;
    help(root->right,pre);
    return head;
}

Node * bToDLL(Node *root)
{
    // your code here
     if(root == NULL)   return NULL;
    Node* head = NULL;
    return help(root,head);
}

It’s getting accepted as you can see here

I cannot understand the issue with my code.

There were only 2 sections of your code which were causing error In accepting your code and they were

And

Also the return statement in which I have returned the head
Rest it’s same

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.