Why RunTime Error ?


  • 0
    B
    #define DELTA 15
    typedef struct _path {
        int *ns;
        int n;
        int capacity;
    }path;
    typedef struct _sol {
        char **ps;
        int n;
        int capacity;
    }sol;
    
    char *itoa (int n)
    {
        static char res[13];
        int i = 0, j = 0;
    
        if (n < 0) {
            ++i;
            res[j++] = '-';
            n = -n;
        }
        do {
            res[j++] = n % 10 + '0';
            n /= 10;
        } while (n);
        res[j--] = '\0';
        for (; i < j; ++i, --j) {
            if (res[i] != res[j]) {
                res[i] ^= res[j]; res[j] ^= res[i]; res[i] ^= res[j];
            }
        }
    
        return res;
    }
    char *saveSOL (path *pPath)
    {
        int len = 50, i, n, l;
        char *pszResult, *pszNum;
    
        pszResult = (char *)malloc (sizeof (char) * len);
        for (n = i = 0; i < pPath->n; ++i) {
            pszNum = itoa (pPath->ns[i]);
            l = strlen (pszNum);
            if (n + l + 2 >= len) {
                pszResult = (char *)realloc (pszResult, len += DELTA);
            }
            strcpy (pszResult + n, pszNum);
            n += l;
            if (i < pPath->n - 1) {
                pszResult[n++] = '-';
                pszResult[n++] = '>';
            }
        }
        pszResult[n] = '\0';
        return pszResult;
    }
    void DFS (struct TreeNode *root, path *pPath, sol *pSOL)
    {
        if (!root) {
            return ;
        }
        if (pPath->capacity == pPath->n) {
            pPath->ns = (int *)realloc (pPath->ns, pPath->capacity += DELTA);
        }
        pPath->ns[pPath->n++] = root->val;
        if (!root->left && !root->right) {
            if (pSOL->n == pSOL->capacity) {
                pSOL->ps = (char **)realloc (pSOL->ps, pSOL->capacity += DELTA);
            }
            pSOL->ps[pSOL->n++] = saveSOL (pPath);
        }
        DFS (root->left, pPath, pSOL);
        DFS (root->right, pPath, pSOL);
        pPath->n--;
    }
    char** binaryTreePaths(struct TreeNode* root, int* returnSize)
    {
        path PT;
        sol SOL;
    
        PT.ns = NULL, PT.n = PT.capacity = 0;
        SOL.ps= NULL, SOL.n= SOL.capacity= 0;
    
        DFS (root, &PT, &SOL);
        *returnSize = SOL.n;
    
        return SOL.ps;
    }

Log in to reply
 

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