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

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

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

具体序列化结果如下:

#include <iostream>  
using namespace std;  
struct BinaryTree  
{  
    int data;  
    BinaryTree *pLeft;  
    BinaryTree *pRight;  
};  
int Data[15]={0};  
static int count=0;  
static int count1=-1;  
BinaryTree *pRoot=NULL;  
BinaryTree *pRoot1=NULL;  
void CreateTree(BinaryTree * &root)  
{  
    int data;  
    cin>>data;  
    if(0==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++]=0;  
        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 0;  
}

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

 

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

posted @ 2017-10-11 15:43  邱进宝  阅读(170)  评论(0编辑  收藏  举报