一、四种遍历
前序遍历、中序遍历、后序遍历、层序遍历
#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
class Node{
public:
int val;
Node *left;
Node *right;
Node(int val) :val(val), left(NULL), right(NULL) {}
};
二、敲代码:序列化、反序列化
1、前序遍历
(1)前序遍历 - 序列化
void front_seq(Node *root, queue<string> &q) {
if (root == NULL) {
q.push("#");
return;
}
string s = to_string(root->val);
q.push(s);
front_seq(root->left, q);
front_seq(root->right, q);
}
(2)前序遍历 - 反序列化
Node* front_reverse(queue<string> &q) {
string s = q.front();
q.pop();
if (s == "#") {
return NULL;
}
int t = stoi(s);
Node *p = new Node(t);
p->left = front_reverse(q);
p->right = front_reverse(q);
return p;
}
2、层序遍历
(1)层序遍历 - 序列化
void level_seq(Node *root, queue<string> &q) {
if (root == NULL) {
q.push("#");
return;
}
queue<Node *> qt;
qt.push(root);
string s = to_string(root->val);
q.push(s);
while (!qt.empty()) {
int qs = qt.size();
while (qs--) {
Node *qf = qt.front();
qt.pop();
if (qf->left != NULL) {
qt.push(qf->left);
string s = to_string(qf->left->val);
q.push(s);
}
else {
q.push("#");
}
if (qf->right != NULL) {
qt.push(qf->right);
string s = to_string(qf->right->val);
q.push(s);
}
else {
q.push("#");
}
}
}
}
(2)层序遍历 - 反序列化
Node *level_reverse(queue<string> &q) {
// 先把根放入节点队列
string s = q.front();
q.pop();
if (s == "#") {
return NULL;
}
queue<Node *> qt;
Node *root = new Node(stoi(s));
qt.push(root);
// 补充队列中每个节点的左右节点
while (!qt.empty()) {
Node *qtf = qt.front(); // 从节点队列中取一个节点
qt.pop();
string s = q.front(); // 从字符串队列中取两个字符串
q.pop();
if (s != "#") {
Node *p = new Node(stoi(s));
qtf->left = p;
qt.push(p); // 进队
}
else {
qtf->left = NULL;
}
s = q.front();
q.pop();
if (s != "#") {
Node *p = new Node(stoi(s));
qtf->right = p;
qt.push(p); // 进队
}
else {
qtf->right = NULL;
}
}
return root;
}