C solution 92%


  • 0
    I
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    
    #include <string.h> /* stpcpy */
    
    static char     *ft_itoa(int v)
    {
    	static char		buf[0x15];
    	char			*p = buf + 0x14;
    
    	if (v >= 0)
    	{
    		*--p = '0' + (v % 10);
    		while (0 != (v /= 10))
    			*--p = '0' + (v % 10);
    	}
    	else
    	{
    		*--p = '0' - (v % 10);
    		while (0 != (v /= 10))
    			*--p = '0' - (v % 10);
    		*--p = '-';
    	}
    	return (p);
    }
    
    #define CALL_CHILD(buf, node)           \
        do {                                \
            *(*buf)++ = '(';                \
            ft_fill_from_tree(buf, node);   \
            *(*buf)++ = ')';                \
        } while (0)
    
    static void     ft_fill_from_tree(char **p, struct TreeNode *root)
    {
        if (0 == root)
            return ;
        *p = stpcpy(*p, ft_itoa(root->val));
        if (0 != root->left || 0 != root->right)
            CALL_CHILD(p, root->left);
        if (0 != root->right)
            CALL_CHILD(p, root->right);
    }
    
    char            *tree2str(struct TreeNode* t)
    {
        static char buf[0x1000];
        char        *p = buf;
        
        ft_fill_from_tree(&p, t);
        *p = 0;
        return (buf);
    }
    

Log in to reply
 

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