C runtime error , but result is right


  • 0
    C
        #define max(a, b) (a)>(b)?(a):(b)
    int height(struct TreeNode *root){
        if(root==NULL){
            return 0;
        }
        int lh=height(root->left);
        int rh=height(root->right);
        return 1+max(lh, rh);
    }
    int* postorderTraversal(struct TreeNode* root, int* returnSize) {
        int h=height(root);
        struct TreeNode *stack=(struct TreeNode*)malloc(sizeof(struct TreeNode)*(h+1));
        int current=0;
        if(root==NULL){
            *returnSize=0;
            return NULL;
        }
        stack[current]=*root;
        int *res=(int*)malloc(sizeof(int));
        int index=0;
        while(current>=0){
          //  printf("%d, val %d\n", current, stack[current].val);
            if(stack[current].left!=NULL){
                current++;
                stack[current]=*(stack[current-1].left);
                stack[current-1].left=NULL;
            }else if(stack[current].right!=NULL){
                current++;
                stack[current]=*(stack[current-1].right);
                stack[current-1].right=NULL;
            }else{
                
                res[index]=stack[current].val;
                //printf("res %d\n", res[index]);
                current--;
                index++;
                if(current>=0){
                    res=(int*)realloc(res, sizeof(int)*(index+1));
                }
               
            }
            
        }
        
        free(stack);
        *returnSize=index;
        return res;
    }

Log in to reply
 

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