王道408 二叉排序树
经过几个小时的努力,彩笔终于能让完整的代码运行(之前的二叉树代码都写不全),这个也还有点小瑕疵
#include<stdlib.h>
#include<stdio.h>
#pragma warning(disable : 4996)
typedef int Elemtype;
typedef struct BSTNode {
Elemtype data;
struct BSTNode *lchild, *rchild;
}BSTNode, * BSTree;
//非递归查找算法
BSTNode *BST_Search(BSTree T, Elemtype key) {
while (T != NULL && key != T->data) {//若树为空或等于根节点值,则循环结束
if (key < T->data) {
T = T->lchild; //小于,则在左子树上寻找
}
else {
T = T->rchild; //大于, 则在右子树上寻找
}
}
return T;
}
//递归插入算法
int BST_Insert(BSTree&T, Elemtype k) {
if (T == NULL) { //原树或节点为空,插入新记录为根节点
T = (BSTree)malloc(sizeof(BSTNode));
T->data = k;
T->lchild = T->rchild = NULL;
return 1; //返回1插入成功
}
else if (k == T->data) { //树中有相同的值,插入失败
return 0;
}
else if (k < T->data) {
return BST_Insert(T->lchild, k);//插入到左子树
}
else {
return BST_Insert(T->rchild, k);//插入到右子树
}
}
//非递归插入算法(报错了,迟点修改)
int BST_Insert2(BSTree&T, Elemtype k) {
while (k != T->data) {
if (T == NULL) { //原树或节点为空,插入新记录为根节点
T = (BSTree)malloc(sizeof(BSTNode));
T->data = k;
T->lchild = T->rchild = NULL;
return 1; //返回1插入成功
}
else if (k < T->data) {
T=T->lchild;//插入到左子树
}
else {
T=T->rchild;//插入到右子树
}
}return 0;
}
//中序输出
void print(BSTree T) {
if (T != NULL) {
print(T->lchild);
printf("%d ", T->data);
print(T->rchild);
}
}
void Creat_BST(BSTree &T, Elemtype str[], int n) {
T = NULL; //初始化T为空树
int i = 0;
while (i < n) { //依此将每个关键字插入到二叉排序树中
BST_Insert(T, str[i]);
i++;
}
}
int main(){
BSTree T;
int str[10],a,i=0;
printf("输入个数小于10\n");
scanf("%d", &a);
while (a!= 233&&i!=9) {
str[i] = a;
i++;
scanf("%d", &a);
}
Creat_BST(T, str, i);
if (BST_Insert(T, 25)) {
printf("插入成功\n");
}
else {
printf("插入失败\n");
}
print(T);
}
运行结果
太感人了,昨天一晚上0提升,今天搞出来一个