什么是广义表?
之前我们探究了如何进行二叉树的前序遍历,二叉树序列化只是在其基础上加上括号和逗号而已。
关键代码如下:
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;
}
运行结果:
之后会更新广义表转二叉树的代码哦!