二叉树的持久化(序列化和反序列化)

一开始我以为是ACM的可持久化数据结构。。。后来了解一下发现不是这样,然后看多两眼。。。好像上课有讲这东西,居然忘了。。

二叉树持久化是指用某种方式将一棵二叉树以字符串形式保存,之后再根据这个字符串还原出来。

用途:保存信息,传递信息。

普遍的方法是先序遍历,碰到空节点则加'#',普通节点则为val+',',实现感觉是很容易的,对于原ACMER的我来说。下面直接给代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
using namespace std;

struct Tree{
	int data;
	Tree *left, *right;
};

void deserialize(Tree* &root,string &str,int &pos){
	if ('#' == str[pos]){
		pos++;
		root = NULL;
		return;
	}
	int data = 0;
	while (str[pos] != ',')
		data = data * 10 + str[pos++] - '0';
	pos++;
	root = (Tree *)malloc(sizeof(Tree));
	root->data = data;
	deserialize(root->left, str, pos);
	deserialize(root->right, str, pos);
}

void serialize(Tree *root, string &str){
	if (!root){
		str += '#';
		return;
	}
	str += to_string(root->data);
	str += ',';
	serialize(root->left, str);
	serialize(root->right, str);
}

void destroy(Tree* root){
	if (NULL == root)
		return;
	destroy(root->left);
	destroy(root->right);
	free(root);
}

int main(){
	string str = "123,213,4,##5,##3,6,###";
	int pos = 0;
	Tree *root = new Tree;
	deserialize(root, str, pos);
	string temp = "";
	serialize(root, temp);
	cout << temp << endl;
	destroy(root);
}

猜你喜欢

转载自blog.csdn.net/qq_34262582/article/details/80328201