题目:
请实现两个函数,分别用来序列化和反序列化二叉树
思路:
这一题尤为头疼,可能是对于数据流,iostream这些东西不是很明白,所以暂且搁下吧,以下为何海涛在Github上的源码,但是这个与牛客的格式略有不同,因此可能过不了牛客OJ的编译。
程序代码:
void Serialize(const BinaryTreeNode* pRoot, ostream& stream)
{
if(pRoot == nullptr)
{
stream << "$,";
return;
}
stream << pRoot->m_nValue << ',';
Serialize(pRoot->m_pLeft, stream);
Serialize(pRoot->m_pRight, stream);
}
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;
}
void Deserialize(BinaryTreeNode** pRoot, istream& stream)
{
int number;
if(ReadStream(stream, &number))
{
*pRoot = new BinaryTreeNode();
(*pRoot)->m_nValue = number;
(*pRoot)->m_pLeft = nullptr;
(*pRoot)->m_pRight = nullptr;
Deserialize(&((*pRoot)->m_pLeft), stream);
Deserialize(&((*pRoot)->m_pRight), stream);
}
}