二叉树的代码实现

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct Node {
	int data;
	struct Node* lchild, * rchild;
}Node;
typedef struct Tree {
	Node* root;
	int length;
}Tree;
Node* get_newNode(int val) {
	Node* p = (Node*)malloc(sizeof(Node));
	p->data = val;
	p->lchild = p->rchild = nullptr;
	return p;
}
Tree* get_newTree() {
	Tree* t = (Tree*)malloc(sizeof(Tree));
	t->root = nullptr;
	t->length = 0;
	return t;
}
Node* insert_node(Node* root, int val, int *flag) {
	if (root == nullptr) {
		*flag = 1;
		return get_newNode(val);
	}
	if (root->data == val)return root;
	if (root->data > val)root->lchild = insert_node(root->lchild, val, flag);
	else root->rchild = insert_node(root->rchild, val, flag);
	return root;
}
void insert(Tree* t, int val) {
	if (t == nullptr)return;
	int flag = 0;
	t->root = insert_node(t->root, val, &flag);
	t->length += flag;
	return;
}
void clear_node(Node* node) {
	if (node == nullptr)return;
	clear_node(node->lchild);
	clear_node(node->rchild);
	free(node);
}
void clear(Tree* t) {
	if (t == nullptr)return;
	clear_node(t->root);
	free(t);
	return;
}
void pre_order_node(Node* root) {
	if (root == nullptr)return;
	printf("%d ", root->data);
	pre_order_node(root->lchild);
	pre_order_node(root->rchild);
	return;
}
void pre_order(Tree* t) {
	if (t == nullptr)return;
	printf("pre_order : ");
	pre_order_node(t->root);
	printf("\n");
	return;
}
void in_order_node(Node* root) {
	if (root == nullptr)return;
	in_order_node(root->lchild);
	printf("%d ", root->data);
	in_order_node(root->rchild);
	return;
}
void in_order(Tree* t) {
	if (t == nullptr)return;
	printf("in_order : ");
	in_order_node(t->root);
	printf("\n");
	return;
}

void post_order_node(Node* root) {
	if (root == nullptr)return;
	post_order_node(root->lchild);
	post_order_node(root->rchild);
	printf("%d ", root->data);
	return;
}
void post_order(Tree* t) {
	if (t == nullptr)return;
	printf("post_order : ");
	post_order_node(t->root);
	printf("\n");
	return;
}
void output_node(Node* root) {
	if (root == nullptr)return;
	printf("%d", root->data);
	if (root->lchild == nullptr && root->rchild == nullptr)return;
	printf("(");
	output_node(root->lchild);
	printf(",");
	output_node(root->rchild);
	printf(")");
	return;
}

void output(Tree* t) {
	if (t == nullptr)return;
	printf("tree(%d) : ", t->length);
	output_node(t->root);
	printf("\n");
}
int main() {
	srand(time(0));
	Tree* tree = get_newTree();
#define MAX 10
	for (int i = 1; i <= 10; i++) {
		int val = rand() % 100;
		insert(tree, val);
		output(tree);
	}
	pre_order(tree);
	in_order(tree);
	post_order(tree);
#undef MAX
	clear(tree);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值