题目描述:请实现两个函数,分别用来序列化和反序列化二叉树
把书上给的例程贴过来感受一下吧,题目说得太不清晰。
总之下面代码实现的就是,前序遍历实现把一棵树的节点值输出成字符串的序列化,和根据字符串还原成树的反序列化过程。
例子:
代码:
//序列化过程
void Serialize(BinaryTreeNode* pRoot, ostream& stream)
{
if(pRoot == NULL)
{
stream << "$,";
return;
}
stream << pRoot->m_nValue << ',';
Serialize(pRoot->m_pLeft, stream);
Serialize(pRoot->m_pRight, stream);
}
反序列化过程:
void Deserialize(BinaryTreeNode** pRoot, istream& stream)
{
int number;
if(ReadStream(stream, &number))
{
*pRoot = new BinaryTreeNode();
(*pRoot)->m_nValue = number;
(*pRoot)->m_pLeft = NULL;
(*pRoot)->m_pRight = NULL;
Deserialize(&((*pRoot)->m_pLeft), stream);
Deserialize(&((*pRoot)->m_pRight), stream);
}
}
//ReadStream实现每次读出一个数字或者一个字符'$',如果是数字返回true,否则返回false
bool ReadStream(istream& stream, int* number)
{
if(stream.eof())
return false;
char buffer[32];
buffer[0] = '\0';
char ch;
stream >> ch;
int i = 0;
while(!stream.eof() && ch != ',')
{
buffer[i++] = ch;
stream >> ch;
}
bool isNumeric = false;
if(i > 0 && buffer[0] != '$')
{
*number = atoi(buffer);
isNumeric = true;
}
return isNumeric;
}