数据结构:二叉树的序列化、反序列化

一、四种遍历

        前序遍历、中序遍历、后序遍历、层序遍历

#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;
}

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值