C accepted solution


  • 0
    L
    int maxTreeHeight (struct TreeNode *ptr) {
        int p, q;
        if (ptr == NULL) return 0;
        p = maxTreeHeight (ptr->left);
        q = maxTreeHeight (ptr->right);
        return p > q ? p + 1 : q + 1;
    }
    
    void cunt (struct TreeNode* ptr, int target, int current, int *size_ptr) {
        if (!ptr) return;
        if (target == current) {
            (*size_ptr)++;
            return;
        }
        cunt (ptr->left, target, current + 1, size_ptr);
        cunt (ptr->right, target, current + 1, size_ptr);
    }
    
    void fill (struct TreeNode* ptr, int target, int current, int *index, int *lv_ptr) {
        if (!ptr) return;
        if (target == current) {
            lv_ptr[*index] = ptr->val;
            ++*index;
            return;
        }
        fill (ptr->left, target, current + 1, index, lv_ptr);
        fill (ptr->right, target, current + 1, index, lv_ptr);
    }
    
    int** levelOrderBottom(struct TreeNode* root, int** columnSizes, int* returnSize) {
        int i, j, **arr_ptr, size, index;
        if (root == NULL) return NULL;
        *returnSize = maxTreeHeight(root);
        arr_ptr = (int **)malloc(*returnSize * sizeof(int *));
        *columnSizes = (int *)malloc(*returnSize * sizeof(int));
        for (i = *returnSize;i > 0; i--) {
            j = 1;
            size = 0;
            index = 0;
            cunt (root, i, j, &size);
            (*columnSizes)[*returnSize - i] = size;
            arr_ptr[*returnSize - i] = (int *)malloc(size * sizeof(int));
            fill (root, i, j, &index, arr_ptr[*returnSize - i]);
        }
        return arr_ptr;
    }

Log in to reply
 

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