My solution to the question


  • 0
    V
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {            
            ListNode *move = head;
            int num = 0;
            while( move )
            {
                num++;
                move = move->next;
            }
            return sortedListToBST( head, num );
        }
    
        TreeNode *sortedListToBST( ListNode *head, int num ) {
            if( num == 0 )
                return nullptr;
            if( num == 1 )
                return new TreeNode( head->val );
            
            ListNode *move = head;
            for( int i = 1; i < num / 2; i++ )
                move = move->next;
        
            auto root = new TreeNode( move->next->val );
            root->left = sortedListToBST( head, num / 2 );
            root->right = sortedListToBST( move->next->next, ( num - 1 ) / 2 );
            move->next = nullptr;
            return root;
        }
    };

Log in to reply
 

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