#include<stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
#define maxSize 100
typedef struct BTNode
{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode; // 二叉排序树的结构体
BTNode* BSTSearch(BTNode *bt,int key) //查找关键字并返回的是指针型
{
if(bt==NULL)
return NULL;
else
{
if(bt->key==key)
return bt;
else if(key<bt->key)
return BSTSearch(bt->lchild,key);
else
return BSTSearch(bt->rchild,key);
}
}
int BSTInsert(BTNode *&bt,int key) //插入一个关键字
{
if(bt==NULL)
{
bt=(BTNode*)malloc(sizeof(BTNode));
bt->lchild=bt->rchild=NULL;
bt->key=key;
return 1;
}
else
{
if(bt->key==key)
return 0;
else if(key<bt->key)
return BSTInsert(bt->lchild,key);
else
return BSTInsert(bt->rchild,key);
}
}
void CreateBST(BTNode *&bt,int n,int key[]) //创造二叉排序树
{
int i=0;
for(i;i<n;i++)
BSTInsert(bt,key[i]);
}
void inorder(BTNode *bt) //一个中序遍历判断是否构建完成
{
if(bt!=NULL)
{
inorder(bt->lchild);
printf("%d ",bt->key);
inorder(bt->rchild);
}
}
int main(void)
{
int key[ ]={1,2,3,4,5,6};
int n=6;
BTNode *bt;
bt=(BTNode*)malloc(sizeof(BTNode));
bt=NULL; //突然发现把指针指向的地址置为空很重要,不然运行就出错了
CreateBST(bt,n,key);
// BTNode *p=BSTSearch(bt,2);
// cout<<p->key<<endl;
BSTInsert(bt,7);
inorder(bt);
system("pause");
return 0;
}
/*
*/
二叉排序树的查找,插入及创建(C++完整版)
最新推荐文章于 2023-10-17 13:14:48 发布