输入一棵二叉树,将其序列化为char*,并且支持反序列化为二叉树。
解题思路
- 先序遍历二叉树,序列化
- 同先序遍历结构,反序列化
代码运行结果没问题,但是未通过所有测试案例。。。
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include "ListNode.h"
#include "TreeNode.h"
#include "Graph.h"
using namespace std;
#define MAXNUM 100010
#define DRIFT 1001
void Serialize(TreeNode* pRoot, vector<char> &vec){
if(pRoot == nullptr){
vec.push_back('$');
vec.push_back(',');
return ;
}
vec.push_back('0' + pRoot->val);
vec.push_back(',');
Serialize(pRoot->left, vec);
Serialize(pRoot->right, vec);
}
// 序列化二叉树(前序遍历的格式)
char* Serialize(TreeNode* root){
vector<char> vecStr;
Serialize(root, vecStr);
char* str = new char[vecStr.size() + 1];
int i;
for(i = 0; i < (int)vecStr.size(); i++)
str[i] = vecStr[i];
str[i] = ' ';
return str;
}
TreeNode* Deserialize(vector<char> &vec){
if(vec.size() == 0)
return nullptr;
TreeNode* pNode = new TreeNode(vec[vec.size() - 1] - '0');
vec.pop_back();
vec.pop_back();
// 如果读取的是数字
if(vec[vec.size() - 1] >= '0' && vec[vec.size() - 1] <= '9')
pNode->left = Deserialize(vec);
else{
pNode->left = nullptr;
vec.pop_back();
vec.pop_back();
}
// 如果读取的是数字
if(vec[vec.size() - 1] >= '0' && vec[vec.size() - 1] <= '9')
pNode->right = Deserialize(vec);
else{
pNode->right = nullptr;
vec.pop_back();
vec.pop_back();
}
return pNode;
}
// 根据前序遍历的序列化结果,重建二叉树
TreeNode* Deserialize(char *str){
// 根据前序遍历重建
vector<char> vec;
string s = str;
for(int i = s.length() - 1, j = 0; i >= 0; i--)
vec.push_back(s[i]);
return Deserialize(vec);
}
int main()
{
TreeNode* pNode1 = CreateBinaryTreeNode(1);
TreeNode* pNode2 = CreateBinaryTreeNode(2);
TreeNode* pNode3 = CreateBinaryTreeNode(3);
TreeNode* pNode4 = CreateBinaryTreeNode(4);
TreeNode* pNode5 = CreateBinaryTreeNode(5);
TreeNode* pNode6 = CreateBinaryTreeNode(6);
ConnectTreeNodes(pNode2, pNode4, nullptr);
ConnectTreeNodes(pNode3, pNode5, pNode6);
ConnectTreeNodes(pNode1, pNode2, pNode3);
// 如果写为char str[100]返回的话,会报错,不能返回局部变量
char* str = Serialize(pNode1);
cout<<str<<endl;
PrintTree(Deserialize(str));
delete str;
return 0;
}