二叉树广义表

#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;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值