您的位置:首页 > 其它

二叉树的序列化与还原

2015-09-13 20:31 176 查看
遇到一个二叉树序列化的问题,就是用字符串或者数组来表示二叉树,或者使用字符串或者数组来还原二叉树,以下是源程序

#include <iostream>

#include <stack>

#include <string>

using namespace std;

typedef struct _BiTree

{

char data;

struct _BiTree *left;

struct _BiTree *right;

}BiTree,*PBiTree;

PBiTree BuiltTree()

{

char temp;

cin>>temp;

if(temp=='#')

return NULL;

PBiTree root=(PBiTree)malloc(sizeof(BiTree));

root->data=temp;

root->left=BuiltTree();

root->right=BuiltTree();

return root;

}

void PreOrderTree(PBiTree root)

{

if(root==NULL)

{

cout<<"#"<<" ";

return;}

cout<<root->data<<" ";

PreOrderTree(root->left);

PreOrderTree(root->right);

}

string TreeToString(PBiTree root)

{

string str_ret;

if(root==NULL)

return "#";

str_ret=root->data;

str_ret+=TreeToString(root->left);

str_ret+=TreeToString(root->right);

return str_ret;

}

int pos_right=0;//此变量比较重要,意思是检查在进行右递归时候,从哪个下标开始进行

PBiTree StringToTree(string str,int pos)

{

if(str.at(pos)=='#')

{

pos_right=pos+1;

return NULL;

}

PBiTree ret=(PBiTree)malloc(sizeof(BiTree));

ret->data=str.at(pos);

ret->left=StringToTree(str,pos+1);

ret->right=StringToTree(str,pos_right);

return ret;

}

int main()

{

PBiTree root;

root=BuiltTree();

//PreOrderTree(root);

string tree_string;

tree_string=TreeToString(root);

cout<<"This is the string convertted from tree"<<endl;

cout<<tree_string<<endl;

PBiTree recv;

recv=StringToTree(tree_string,0);

cout<<"This is the tree convertted from string"<<endl;

PreOrderTree(recv);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: