07.数据结构之二叉树

树的定义

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值