二叉树的序列化与还原

来源:互联网 发布:软件开发的生命周期 编辑:程序博客网 时间:2024/05/17 08:19

遇到一个二叉树序列化的问题,就是用字符串或者数组来表示二叉树,或者使用字符串或者数组来还原二叉树,以下是源程序


#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;
}
0 0
原创粉丝点击