C solution (0ms) - using asprintf to dynamically grow the path buffer


  • 0
    void binaryTreePathsHelper(struct TreeNode *node, char ***result, int *resultSize, char *path) {
        if (!node) return;
        char *newPath = NULL;
        if (node->left == NULL && node->right == NULL) {
            asprintf(&newPath, "%s%d", path, node->val);
            *result = realloc(*result, ++(*resultSize) * sizeof(char **));
            (*result)[*resultSize - 1] = newPath;
            return;   
        }
        asprintf(&newPath, "%s%d->", path, node->val);
        binaryTreePathsHelper(node->left, result, resultSize, newPath);
        binaryTreePathsHelper(node->right, result, resultSize, newPath);
        free(newPath);
    }
    
    char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
        if (!root) return NULL;
        char **result = NULL;
        binaryTreePathsHelper(root, &result, returnSize, "");
        return result;
    }
    

Log in to reply
 

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