very simple C solution,only with one Auxiliary func,6ms


  • 0
    W
    void helper(struct TreeNode* root,char ***ret,int* returnSize,int index){
    	int slen=strlen((*ret)[index]);
    	(*ret)[index]=(char*)realloc((*ret)[index],(slen+10)*sizeof(char));
    	char *stmp=(char*)calloc(10,sizeof(char));
    	sprintf(stmp,"%d",root->val);
    	strcat((*ret)[index],stmp);
    	if(root->left==NULL && root->right==NULL) return;
    	else if(root->left!=NULL && root->right==NULL){
    		(*ret)[index]=(char*)realloc((*ret)[index],sizeof(char)*(strlen((*ret)[index])+3));
    		strcat((*ret)[index],"->");
    		helper(root->left,ret,returnSize,index);
    	}
    	else if(root->left==NULL && root->right!=NULL){
    		(*ret)[index]=(char*)realloc((*ret)[index],sizeof(char)*(strlen((*ret)[index])+3));
    		strcat((*ret)[index],"->");
    		helper(root->right,ret,returnSize,index);
    	}
    	else{
    		(*ret)[index]=(char*)realloc((*ret)[index],sizeof(char)*(strlen((*ret)[index])+3));
    		strcat((*ret)[index],"->");
    		*returnSize+=1;
    		*ret=(char**)realloc(*ret,(*returnSize)*sizeof(char*));
    		(*ret)[*returnSize-1]=(char*)calloc(strlen((*ret)[index])+1,sizeof(char));
    		strcpy((*ret)[*returnSize-1],(*ret)[index]);
    		int tmp=*returnSize-1;
    		helper(root->left,ret,returnSize,index);
    		helper(root->right,ret,returnSize,tmp);
    	}
    	
    }
    char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
        char **ret=NULL;
        if(root==NULL) return NULL;
        else{
        	ret=(char**)calloc((*returnSize+1),sizeof(char*));
        	ret[0]=(char*)calloc(0,sizeof(char));
        	*returnSize+=1;
        	helper(root,&ret,returnSize,0);
        }
        return ret;
    }
    

Log in to reply
 

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