题目
收获
1:又巩固了一遍二叉树的创建过程已经先序遍历输出的过程(遇到的一个小问题就是在创建二叉树的时候判断直接进行返回了没有进行root=NULL:的赋值,这里最开始弄得还不是很透彻~,现在较为清晰了在创建的时候赋值NULL的重要性
2:在使用to_string()函数的时候报错了,因为了编译器不支持的问题,参考了网上的博客进行了修改~参考链接
3:对字符串的相关操作更加熟悉了一些,以及地址(*str)++等的操作和**str的意思等~(后期还要继续巩固使用)
代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct TreeNode{
TreeNode *left;
TreeNode *right;
int val;
}*BiTree,TreeNode;
//先序遍历创建方法
void CreateTreePre(BiTree &root){
int num;
cin>>num;
if(num==-1){
root=NULL;
return ;
}
else{
root=new TreeNode;
root->val=num;
CreateTreePre(root->left);
CreateTreePre(root->right);
}
}
//层次遍历创建方法
void CreateTreeLevel(BiTree &root){
int num;
cin>>num;
if(num==-1)
return ;
queue<TreeNode*>q;
root=new TreeNode;
root->val=num;
TreeNode* cur=root;
q.push(cur);
while(!q.empty()){
cur=q.front();
q.pop();
cin>>num;
if(num==-1){
cur->left==NULL;
}else{
cur->left=new TreeNode;
cur->left->val=num;
cur->left->left=cur->left->right=NULL;
q.push(cur->left);
}
cin>>num;
if(num==-1){
cur->right==NULL;
}else{
cur->right=new TreeNode;
cur->right->val=num;
cur->right->left=cur->right->right=NULL;
q.push(cur->right);
}
}
}
// 处理序列化函数的功能
void SerializeFunction(TreeNode *root,string &str){
if(root==NULL){
str+="#";
return;
}
string temp=to_string(root->val);
str+=temp+'!';
SerializeFunction(root->left, str);
SerializeFunction(root->right, str);
}
char* Serialize(TreeNode *root) {
if(root==NULL)
return "#";
string res;
SerializeFunction(root, res);
char* charRes=new char[res.length()+1];
strcpy(charRes, res.c_str());
charRes[res.length()]='`';
return charRes;
}
// 处理反序列化的功能函数
TreeNode* DeserializeFunction(char** str){
if(**str=='#'){
(*str)++;
return NULL;
}
// 数字转换
int val=0;
while(**str!='!'&&**str!='`'){
val=val*10+((**str)-'0');
(*str)++;
}
TreeNode*root=new TreeNode;
root->val=val;
if(**str=='`')
return root;
else
(*str)++;
root->left=DeserializeFunction(str);
root->right=DeserializeFunction(str);
return root;
}
TreeNode* Deserialize(char *str) {
if(str=="#"){
return NULL;
}
TreeNode *res=DeserializeFunction(&str);
return res;
}
//先序遍历输出二叉树
void printTreePre(TreeNode *root){
if(root==NULL)
return;
else{
TreeNode*cur=root;
cout<<cur->val;
printTreePre(root->left);
printTreePre(root->right);
}
}
int main()
{
BiTree root;
CreateTreePre(root);
cout<<"二叉树创建成功!!"<<endl;
cout<<"序列化后的结果为:"<<endl;
char * str=Serialize(root);
cout<<str<<endl;
cout<<"反序列化后的结果为:"<<endl;
root=Deserialize(str);
printTreePre(root);
return 0;
}