A novel way to sovle the problem! 48ms Accepted C++ code presented.


  • 0
    X
    class Codec {
    public:
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            if(root == NULL)
            {
                return "0";
            }
            else
            {
                string result;
                result.append(itos(root->val));
                result.append(serialize(root->left));
                result.append(serialize(root->right));
                return result;
            }
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            int item, iter = 0;
            std::stack<TreeNode **> s;
            TreeNode * root = NULL, ** tmp = NULL;
            s.push(& root);
            while(!s.empty())
            {
                tmp = s.top();
                s.pop();
                if(data[iter ++] == '0')
                {
                	continue;
                }
               	item = stoi(data[iter], data[iter + 1], data[iter + 2], data[iter + 3]);
               	iter += 4;
               	cout << item << endl;
                *tmp = new TreeNode(item);
                s.push(& ((*tmp)->right));
                s.push(& ((*tmp)->left));
            }
            return root;
        }
    
        string itos(int num)
        {
        	string result;
        	char c = '1';
        	result.push_back(c); 
        	char * ptr = (char *)(& num);
        	memcpy(&c, ptr ++, sizeof(char));
    		result.push_back(c); 
    		memcpy(&c, ptr ++, sizeof(char));
    		result.push_back(c); 
    		memcpy(&c, ptr ++, sizeof(char));
    		result.push_back(c); 
    		memcpy(&c, ptr ++, sizeof(char));
    		result.push_back(c); 
    		return result;	
        }
        int stoi(char c1, char c2, char c3, char c4)
        {
        	int num = 0;
    		char * ptr = (char *)(& num);
    	        memcpy(ptr ++, & c1, sizeof(char));
    	        memcpy(ptr ++, & c2, sizeof(char));
    	   	memcpy(ptr ++, & c3, sizeof(char));
    	   	memcpy(ptr ++, & c4, sizeof(char));
    	   	return num;
        }
    };

Log in to reply
 

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