How to show the [] in the C code


  • 0
    L

    HI Everyone:
    I am solving this problem using C, but I have problem. When the input is [], the OJ expect the output is []. But my output always is [Null]. Can anyone tell me how to fix it??

    By the way, what is the meaning of returnSize? I consider it as the number of output strings.

    Here are part of my C code, the rest of the code still constructing

     /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    void PathRecorder(struct TreeNode* root, char** result) {
        if (!root){
            return;
        }
        else if (!root->left && !root->right ){
            result[0] = "1";
        }
        else if (!root->left && root->right){
            result[0] = "2";
        }
        else if (root->left && !root->right){
            result[0] = "3";
        }
        else {
            result[0] = "4";
        }
    } 
     
    char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
        
        char **result = malloc(sizeof(char*));;
        *returnSize = 1;
        PathRecorder(root, result);
        return result;
    }

  • 0

    Yes, like the specification says, *returnSize shall be the size of the array, i.e., the number of output strings. You set it to 1, meaning you say there is one element in the array. Input [] means root is null, so you don't do anything and that one element is whatever was in there from malloc, which apparently happens to be a null pointer. To get output [], you need to set *returnSize to 0.


  • 0
    L

    Thank you. I'll try it


Log in to reply
 

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