二叉搜索树又叫二叉查找树,一个重要应用是他们在查找中的使用。对于二叉搜索树要求对于每个节点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;
}