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

一开始我以为是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);
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值