A simple C solution


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    char result[100000]={0};
    int j;
    struct TreeNode* t1;
    void preorder(struct TreeNode* t,int flag)
    { 
        if(t==NULL) 
        {
            if(flag==0&&t1->right!=NULL)
            {
                result[j]='(';
                j++;
                result[j]=')';
                j++;
            }
            return;
        }
        result[j]='(';
        j++;
        j=j+sprintf(result+j, "%d", t->val);
        t1=(struct TreeNode*)malloc(sizeof(struct TreeNode));
        t1=t;
        preorder(t->left,0); 
        preorder(t->right,1);
        result[j]=')';
        j++;
    }
    char* tree2str(struct TreeNode* t) {
        j=0;
        if(t==NULL) 
        {
            result[j]='\0';
            j++;
            return result;              
        }
        j=j+sprintf(result+j, "%d", t->val);
        t1=(struct TreeNode*)malloc(sizeof(struct TreeNode));
        t1=t;
        preorder(t->left,0);
        preorder(t->right,1);
        result[j]=NULL;
        return result;
    }
    

Log in to reply
 

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