LeetCode 114 - Flatten Binary Tree to Linked List: Runtime Error


  • 0
    A

    My code shows Runtime Error, even though it is working fine on both ideone as well as my local compiler.
    Can somebody please tell me, what I might be missing.

     /**void print(TreeNode *root){     ///Function to check if the list is correct
        while(root){
            cout<<root->val<<"  ";
            root = root->right;
        }
        cout<<endl;
     }**/
    
    TreeNode* reverse(TreeNode *root){
        TreeNode *curr=root,*next,*prev=NULL;
        while(curr){
            next = curr->right;
            curr->right = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    
    void flattenUtil(TreeNode* root, TreeNode* &prev, TreeNode* &newHead){
        if(!root)   return;
        flattenUtil(root->right,prev,newHead);
        flattenUtil(root->left,prev,newHead);
        if(!newHead)    newHead=root;
        else            prev->right=root;
        prev = root;
        root->right = NULL;
    }
    
    void flatten(TreeNode* root) {
        if(!root)   return;
        TreeNode *newHead=NULL,*prev=NULL;
        flattenUtil(root,prev,newHead);
        root = newHead;
        root = reverse(root);
        ///print(root);         /// Testing answer
    }

Log in to reply
 

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