#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#define KEY(n) (n ? n->key : -1)//如果有值则输出当前值,没值输出-1
typedef struct Node {
int key;
Node* lchild, * rchild;
}Node;
Node* getNewNode(int key) {
Node* p = (Node*)malloc(sizeof(Node));
p->key = key;
p->lchild = p->rchild = NULL;
return p;
}
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;
}
void clear(Node* root) {
if (root == NULL)return;
if (root->lchild)clear(root->lchild);
if (root->rchild)clear(root->rchild);
clear(root);
return;
}
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));//memset初始化指buff全部用0来替换
len = 0;
__serialize(root);
return;
}
void print(Node* node) {
printf("%d(%d,%d)\n", KEY(node)
, KEY(node->lchild)
, KEY(node->rchild));
}
void output(Node* root) {
if (root == NULL)return;
print(root);
output(root->lchild);
output(root->rchild);
return;
}
int main() {
srand(time(0));
#define MAX_OP 10
Node* root = getRandomBinaryTree(MAX_OP);//生成一颗10个节点的随机二叉树
serialize(root);// 序列化二叉树
output(root);//输出二叉树
printf("buff[]:%s\n", buff);//输出序列化
free(root);
return 0;
}
二叉树广义表
最新推荐文章于 2024-07-24 20:55:30 发布