0
点赞
收藏
分享

微信扫一扫

07.数据结构之二叉树

吓死我了_1799 2022-04-13 阅读 65
数据结构

树的定义

typedef struct Node {
	int data;
	struct Node* lchild, * rchild;
}Node;

typedef struct Tree {
	Node* root;
	int length;
}Tree;

创建树

Node* getNewNode(int val) {
	Node* p = (Node*)malloc(sizeof(Node));
	p->data = val;
	p->lchild = p->rchild = NULL;
	return p;
}

Tree* getNewTree() {
	Tree* tree = (Tree*)malloc(sizeof(Tree));
	tree->root = NULL;
	tree->length = 0;
	return tree;
}

清空结点

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

void clear(Tree* tree) {
	if (tree == NULL) return;
	clearNode(tree->root);
	free(tree);
	return;
}

插入操作

Node* insertNode(Node* root, int val,int *flag) {
	if (root == NULL) {
		*flag = 1;
		return getNewNode(val);
	}
	if (root->data == val) return root;
	if (root->data > val) root->lchild = insertNode(root->lchild, val,flag);
	else root->rchild = insertNode(root->rchild, val,flag);
	return root;
}

void insert(Tree* tree, int val) {
	if (tree == NULL) return;
	int flag = 0;
	tree->root = insertNode(tree->root, val,&flag);
	tree->length += flag;
	return;
}

前序遍历

void preOrderNode(Node* root) {
	if (root == NULL) return;
	printf("%d ", root->data);
	preOrderNode(root->lchild);
	preOrderNode(root->rchild);
}

void preOrder(Tree* tree) {
	if (tree == NULL) return;
	printf("preOrder: ");
	preOrderNode(tree->root);
	printf("\n");
}

中序遍历

void midOrderNode(Node* root) {
	if (root == NULL) return;
	midOrderNode(root->lchild);
	printf("%d ", root->data);
	midOrderNode(root->rchild);
}

void midOrder(Tree* tree) {
	if (tree == NULL) return;
	printf("midOrder: ");
	midOrderNode(tree->root);
	printf("\n");
}

后序遍历

void postOrderNode(Node* root) {
	if (root == NULL) return;
	postOrderNode(root->lchild);
	postOrderNode(root->rchild);
	printf("%d ", root->data);
}

void postOrder(Tree* tree) {
	if (tree == NULL) return;
	printf("postOrder: ");
	postOrderNode(tree->root);
	printf("\n");
}

打印操作

void outputNode(Node* root) {
	if (root == NULL) return;
	printf("%d", root->data);
	if (root->lchild == NULL && root->rchild == NULL) return;
	printf("(");
	outputNode(root->lchild);
	printf(",");
	outputNode(root->rchild);
	printf(")");
}

void output(Tree* tree) {
	if (tree == NULL) return;
	printf("tree(%d):", tree->length);
	outputNode(tree->root);
	printf("\n");
	return;
}

测试

int main() {
	srand(time(0));
	Tree* tree = getNewTree();
#define MAX_OP 10
	for (int i = 0; i < MAX_OP; i++) {
		int val = rand() % 100;
		insert(tree, val);
		output(tree);
	}
	preOrder(tree);
	midOrder(tree);
	postOrder(tree);
	clear(tree);
#undef MAX_OP

	return 0;
}
举报

相关推荐

数据结构之二叉树简介

0 条评论