数据结构之二叉搜索树

二叉搜索树又叫二叉查找树,一个重要应用是他们在查找中的使用。对于二叉搜索树要求对于每个节点X,左子树中所有节点的关键字要小于X的关键字,右子树中所有节点的关键字要大于X的关键字。所以对于二叉搜索树的中序遍历正好是各个元素从小到大的排序。

代码实现

头文件 "bst.h"

typedef int ElementType;
struct Node;
typedef struct Node *ptrToNode;
typedef struct Node *BSTree;

//通过循环插入数据
void insertByCycle(BSTree &T,ElementType e);
//通过递归插入数据
void insert(BSTree &T,ElementType e);
//前序遍历
void prePrint(BSTree T);
//中序遍历
void midPrint(BSTree T);
//后序遍历
void behPint(BSTree T);
//销毁
void destory(BSTree &T);

具体实现

#include <stdio.h>
#include <stdlib.h>
#include "bst.h"

struct Node {
	ElementType data;
	ptrToNode left;
	ptrToNode right;
};

/**
 * 递归构建二叉查询树
 */
void insert(BSTree &T, ElementType e) {
	if (T == NULL) {
		T = (ptrToNode) malloc(sizeof(struct Node));
		T->data = e;
		T->left = NULL;
		T->right = NULL;
	} else {
		if (e > T->data) {
			insert(T->right, e);
		} else {
			insert(T->left, e);
		}
	}
}

/**
 * 循环构建二叉查询树
 */
void insertByCycle(BSTree &T, ElementType e) {
	ptrToNode *ptr = &T;
	while (*ptr != NULL) {
		if (e < (*ptr)->data) {
			ptr = &(*ptr)->left;
		} else {
			ptr = &(*ptr)->right;
		}
	}

	*ptr = (BSTree) malloc(sizeof(struct Node));
	if(ptr == NULL){
		printf("malloc failed\n");
		return;
	}
	(*ptr)->data = e;
	(*ptr)->left = NULL;
	(*ptr)->right = NULL;
}

//前序遍历
void prePrint(BSTree T) {
	if (T == NULL) {
		return;
	}
	printf("%d ", T->data);
	prePrint(T->left);
	prePrint(T->right);
}

//中序遍历
void midPrint(BSTree T) {
	if (T == NULL) {
		return;
	}
	midPrint(T->left);
	printf("%d ", T->data);
	midPrint(T->right);
}

//后序遍历
void behPint(BSTree T) {
	if (T == NULL) {
		return;
	}
	behPint(T->left);
	behPint(T->right);
	printf("%d ", T->data);
}

//销毁
void destory(BSTree &T) {
	if (T == NULL) {
		return;
	}
	destory(T->left);
	destory(T->right);
	free(T);
	T = NULL;
}

测试

#include <stdio.h>
#include "bst.h"

int main() {
	BSTree T = NULL;
        //插入数据
	insertByCycle(T, 50);
	insertByCycle(T, 35);
	insertByCycle(T, 30);
	insertByCycle(T, 40);
	insertByCycle(T, 58);
	insertByCycle(T, 57);
	insertByCycle(T, 60);

	midPrint(T);  //中
	printf("\n");
	prePrint(T);  //前
	printf("\n");
	behPint(T);  //后
	destory(T);  //销毁
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值