Simple C 0 ms solution


  • 0
    C

    int* preorderTraversal(struct TreeNode* root, int* returnSize) {

    int *temp = returnSize;
    int j = temp[0]; 
    if (root) {
        /* temp[0] is use to track the length of array*/
        int length = temp [0];
        if ( length == 0) {
            temp  = (int*) malloc (sizeof(int) * 2);
            temp [0] = 1;
            temp [1] = root -> val;
        }
        
        else {
            length++;
            temp  = (int*) realloc (temp , sizeof(int) * (length + 1));
            temp [0] = length;
            temp [length] = root -> val;
        }
        temp  = preorderTraversal(root->left, temp);
        temp  = preorderTraversal(root->right, temp);
    }
    
    /* Recursive back to top */
    if ( j == 0) {
         *returnSize = temp[0];
         int *a = (int*) malloc (sizeof(int) * temp[0]);
         /* Remove temp[0] */
         for ( int k = 1; k <= temp[0]; k++) {
             a[k - 1] = temp[k];
         }
         return a;
        }
     return temp;
    }

Log in to reply
 

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