Easy preorder method


  • 0
    C
    class Codec {
    

    public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root)
    {
    	string steps;
    	serialize(root, steps);
    	return steps;
    }
    
    void serialize(TreeNode* root, string &steps)
    {
    	if (root == NULL) {
    		steps += "#";
    		return;
    	}
    	else {
    		steps += to_string(root->val) + "#";
    		serialize(root->left, steps);
    		serialize(root->right, steps);
    	}
    }
    
    // Decodes your encoded data to tree.
    
    TreeNode* deserialize(string data)
    {
    	int index = 0;
    	return deserialize(data, index);
    }
    
    TreeNode* deserialize(const string &data, int &index)
    {
    	int start = index;
    	if (index >= data.size())
    		return NULL;
    	if (data[index] == '#') {
    		index++;
    		return NULL;
    	}
    	for (; index < data.size(); index++) {
    		if (data[index] == '#')
    			break;
    	}
    	int num = stoi(data.substr(start, index++));
    	TreeNode* root = new TreeNode(num);
    	root->left = deserialize(data, index);
    	root->right = deserialize(data, index);
    	return root;
    }
    

    };


Log in to reply
 

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