[各种面试题] 树的序列化和反序列化

树的序列化和反序列化

这里使用的是Leetcode上的层序遍历的序列化的方法。

string serialize(TreeNode* root)
{
	string seq;
	queue<TreeNode*> Q;
	Q.push(root);
	while(!Q.empty())
	{
		TreeNode* cur=Q.front();
		Q.pop();
		if(cur==NULL)
			seq.push_back('#');
		else
		{
			seq.push_back(cur->val);
			Q.push(cur->left);
			Q.push(cur->right);
		}
	}
	return seq;
}
TreeNode* getNode(string& seq,int p)
{
	if(seq[p]=='#')
		return NULL;
	else 
	{
		return new TreeNode(seq[p]);
	}
}
TreeNode* deserialize(string& seq)
{
	if(seq.empty()||seq[0]=='#')
		return NULL;
	int p=0;
	TreeNode* root=new TreeNode(seq[p++]);
	queue<TreeNode*> Q;
	Q.push(root);
	while(!Q.empty())
	{
		TreeNode* cur=Q.front();
		Q.pop();
		cur->left=getNode(seq,p++);
		cur->right=getNode(seq,p++);
		if(cur->left)
			Q.push(cur->left);
		if(cur->right)
			Q.push(cur->right);
	}
	return root;
}


你可能感兴趣的:([各种面试题] 树的序列化和反序列化)