《剑指offer》:[62]序列化二叉树

时间:2023-03-10 01:56:42
《剑指offer》:[62]序列化二叉树

题目:请实现两个函数,分别来序列化和反序列化二叉树。

方案分析:我们知道通过二叉树的中序和任何一个前或者后续遍历都可以反序列化一棵二叉树,但是这样做有一个缺点就是,序列化的数据不能有重复的数据,否则会出错。另外,在反序列化时,需要知道中序和另外的任意一种序列才行,如果两课二叉树在字符流里读出,且二叉树的数据比较多,则会相当的耗时。所以,这里我们采取前序遍历来完成序列化和反序列化,因为我们都知道用前序遍历创建过二叉树。只不过这里如果一旦遇到NULL结点,我们需要用其他的字符来代替它。这样在反序列化时才不会出错,时间复杂度为O(N)。

具体序列化结果如下:

《剑指offer》:[62]序列化二叉树

#include <iostream>
using namespace std;
struct BinaryTree
{
int data;
BinaryTree *pLeft;
BinaryTree *pRight;
};
int Data[]={};
static int count=;
static int count1=-;
BinaryTree *pRoot=NULL;
BinaryTree *pRoot1=NULL;
void CreateTree(BinaryTree * &root)
{
int data;
cin>>data;
if(==data)
root=NULL;
else
{
root=new BinaryTree;
root->data=data;
CreateTree(root->pLeft);
CreateTree(root->pRight);
}
}
void Serialize(BinaryTree *root) //序列化;
{
if(root==NULL)
{
Data[count++]=;
cout<<"0,";
return;
}
cout<<root->data<<",";
Data[count++]=root->data;
Serialize(root->pLeft);
Serialize(root->pRight);
}
void DeSerialize(BinaryTree *&root)
{
count1++;
if(!Data[count1])
root=NULL;
else
{
root=new BinaryTree;
root->data=Data[count1];
DeSerialize(root->pLeft);
DeSerialize(root->pRight);
}
}
void preorder(BinaryTree *root)
{
if(root)
{
cout<<root->data<<" ";
preorder(root->pLeft);
preorder(root->pRight);
}
}
int main()
{
CreateTree(pRoot);
cout<<"原始序列前序遍历:";
preorder(pRoot);
cout<<endl<<"序列化后输出:";
Serialize(pRoot);
cout<<endl;
DeSerialize(pRoot1);//反序列化;
cout<<"反序列化后的前序遍历输出:";
preorder(pRoot1);
cout<<endl;
system("pause");
return ;
}

代码中NULL值用0代替,序列化与反序列化的运行结果:

《剑指offer》:[62]序列化二叉树

转载:http://blog.csdn.net/gogokongyin/article/details/51788015