笔记:二叉树序列化(转广义表)

本文介绍了如何使用C++实现二叉树的前序遍历序列化,并展示了如何将广义表转化为二叉树,包括随机生成二叉树的示例代码和输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是广义表?

 

 

之前我们探究了如何进行二叉树的前序遍历,二叉树序列化只是在其基础上加上括号和逗号而已。

关键代码如下:

char buff[1000];
int len=0;

void __serialize(Node *root){
	if(root==NULL) return;
	len+=snprintf(buff + len,100,"%d",root->key);//向字符数组中输出信息
	if(root->lchild==NULL&&root->rchild==NULL) return;
	len+=snprintf(buff+len,100,"(");
	__serialize(root->lchild);
	if(root->rchild){
		len+=snprintf(buff+len,100,",");
		__serialize(root->rchild);
	}
	len+=snprintf(buff+len,100,")");
	return;
}

void serialize(Node *root){
	memset(buff,0,sizeof(buff));//初始化buff
	len=0;
	__serialize(root);
	return;
}

测试代码(随机生成二叉树)

#include<iostream>
#include<cstdio>
#include<time.h>
#include<string.h>
#define MAX_NODE 10
#define KEY(n) (n? n->key:-1)
using namespace std;
typedef struct Node{
	int key;
	Node *lchild,*rchild;
}Node;

Node *getNewNode(int key){
	Node *p=new Node;
	p->key = key;
	p->lchild=p->rchild=NULL;
	return p;
}

void clear(Node *root){
	if(root==NULL) return;
	clear(root->lchild);
	clear(root->rchild);
	delete root;
}
Node *insert(Node *root,int key){
	if(root==NULL) return getNewNode(key);
	if(rand()%2) root->lchild = insert(root->lchild,key);
	else root->rchild=insert(root->rchild,key);
	return root;
}

Node *getRandomBinaryTree(int n){
	Node *root=NULL;
	for(int i=0;i<n;i++){
		root=insert(root,rand()%100);
	}
	return root;
} 
char buff[1000];
int len=0;

void __serialize(Node *root){
	if(root==NULL) return;
	len+=snprintf(buff + len,100,"%d",root->key);//向字符数组中输出信息
	if(root->lchild==NULL&&root->rchild==NULL) return;
	len+=snprintf(buff+len,100,"(");
	__serialize(root->lchild);
	if(root->rchild){
		len+=snprintf(buff+len,100,",");
		__serialize(root->rchild);
	}
	len+=snprintf(buff+len,100,")");
	return;
}

void serialize(Node *root){
	memset(buff,0,sizeof(buff));//初始化buff
	len=0;
	__serialize(root);
	return;
}

void print(Node *node){
	printf("%d(%d,%d)\n",KEY(node),
		KEY(node->lchild),
		KEY(node->rchild));
	return;
}

void output(Node *root){
	if(root==NULL) return;
	print(root);
	output(root->lchild);
	output(root->rchild);
	return;
}


int main(){
	srand(time(0));
	Node *root=getRandomBinaryTree(MAX_NODE);
	serialize(root);//调用序列化
	output(root);
	printf("Buff[]:%s\n",buff);
	return 0;
}

运行结果: 

 

之后会更新广义表转二叉树的代码哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值