Same code can work in C++but not C. Dose anyone know why?


  • 0
    L
        class Solution {
        public:
         TreeNode* sortedListToBSTHelper( ListNode* &head, int start, int end){
            if(start>end) return NULL;
            //TreeNode *newNode = new TreeNode(head->val);
            int mid=start+(end-start)/2;
            TreeNode* leftNode=sortedListToBSTHelper(head,start,mid-1);
            //newNode->val=head->val;
            TreeNode *newNode = new TreeNode(head->val);
            head=head->next;
            TreeNode * rightNode=sortedListToBSTHelper(head,mid+1,end);
            newNode->left=leftNode;
            newNode->right=rightNode;
            return newNode;
        }
            TreeNode* sortedListToBST(ListNode* head) {
            ListNode *tempNode;
            tempNode=head;
            int num=0;
            while(tempNode){
                num++;
                tempNode=tempNode->next;
            }
            return sortedListToBSTHelper(head, 1, num);
            }
    };
    

    C version is listed below:

    struct TreeNode *helper(struct ListNode*head,int start, int end);
    struct TreeNode* sortedListToBST(struct ListNode* head) {
        if(head==NULL) return NULL;
        int num=0;
        struct ListNode*temp=head;
        while(temp!=NULL){
            num++;
            temp=temp->next;
        }
        return helper(head,1,num);
    }
    struct TreeNode *helper(struct ListNode *head, int start, int end){
        if(start>end) return NULL;
        int mid=start+(end-start)/2;
        struct TreeNode *left=helper(head,start,mid-1);
        struct TreeNode *newNode=malloc(sizeof(struct TreeNode)*1);
        newNode->val=head->val;
        head=head->next;
        struct TreeNode *right=helper(head,mid+1,end);
        newNode->left=left;
        newNode->right=right;
        return newNode;
    }

Log in to reply
 

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