Did not found the bug!("Time Error Problem when the linked list have only one node it will happen)


  • 0
    D
    { TreeNode* ListToBst(ListNode* head,TreeNode* pre){
        TreeNode* root=new TreeNode(head->val);
        //TreeNode* right=NULL;
        root->left=pre;
        head=head->next;
        if(head){
            TreeNode *right=new TreeNode(head->val);
            root->right=right;
        }
        else{
            root->right=NULL;
        }
        
        return root;
        
    }
    
    
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head) return NULL;
        TreeNode* pre=new TreeNode(head->val);
        head=head->next;
       // if(!head) return pre;
        while(head){
            pre=ListToBst(head,pre);
            if(head->next)
                head=head->next->next;
            else{
                break;
            }
            
            
       }
       
       return pre;
        
        
    
        
    }
    

    }

    };


Log in to reply
 

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