反序列化(层序)
反序列化操作(層序):將序列生成層序遍歷的二叉樹取出string數(shù)組中的每一個str[i]元素,根據(jù)str[i]是否是#進行處理,
(1)當str[i]=="#"時,返回NULL,不創(chuàng)建新節(jié)點
(2)當str[i]!="#"時,創(chuàng)建新的節(jié)點,返回該節(jié)點#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) //根據(jù)s的值
{if (s == "#") //若str[i]的值為#,則不創(chuàng)建節(jié)點return NULL;else //否則,創(chuàng)建節(jié)點并返回{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;
}
總結(jié)
- 上一篇: 序列化(层序遍历)
- 下一篇: VideoCapture类