反序列化操作(层序):将序列生成层序遍历的二叉树
取出string数组中的每一个str[i]元素,根据str[i]是否是#进行处理,
(1)当str[i]=="#"时,返回NULL,不创建新节点
(2)当str[i]!="#"时,创建新的节点,返回该节点
#include <iostream>
#include<queue>
#include <string>
using namespace std;
typedef struct TreeNode
{
string data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}TreeNode;
void levelTraver(TreeNode* T) //层次遍历
{
if (!T)
return;
queue<TreeNode*> Q;
TreeNode* cur = T;
Q.push(cur);
while (!Q.empty())
{
cout << Q.front()->data << " ";
cur = Q.front();
Q.pop();
if (cur->lchild)
Q.push(cur->lchild);
if (cur->rchild)
Q.push(cur->rchild);
}
}
TreeNode* NodebyString(string s) //根据s的值
{
if (s == "#") //若str[i]的值为#,则不创建节点
return NULL;
else //否则,创建节点并返回
{
TreeNode* node = new TreeNode;
node->data = s;
return node;
}
}
TreeNode* levelDeSerialize(string str[]) //层序反序列化
{
int index1 = 0;
TreeNode* T = NodebyString(str[index1++]);
queue<TreeNode*> Q;
if (T != NULL)
Q.push(T);
TreeNode* cur;
while (!Q.empty())
{
cur = Q.front();
Q.pop();
cur->lchild = NodebyString(str[index1++]);
cur->rchild = NodebyString(str[index1++]);
if (cur->lchild)
Q.push(cur->lchild);
if (cur->rchild)
Q.push(cur->rchild);
}
return T;
}
int main()
{
string str[] = { "1", "2", "3", "#", "4", "5", "#", "#", "#", "#", "#" };
TreeNode* T = levelDeSerialize(str); //反序列化
cout << "层序遍历" << endl;
levelTraver(T);
return 0;
}
反序列化(层序)
最新推荐文章于 2023-04-12 17:08:34 发布