查找算法
插入算法
代码:
#include<iostream>
using namespace std;
#define ENDFLAG 2022
typedef int KeyType;
typedef char InfoType;
typedef struct{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
//二叉树插入
void Insert_BSTree(BSTree &T,ElemType e){
if(!T){ //树为空,插入根结点
T=new BSTNode;
T->data.key=e.key;
T->lchild=NULL;
T->rchild=NULL;
}
else{
if(e.key<T->data.key) Insert_BSTree(T->lchild,e); //要插入的元素比根结点值小,插入在左子树
else Insert_BSTree(T->rchild,e); //要插入的元素比根结点值大,插入在右子树
}
}
//二叉树的创建
void Create_BSTree(BSTree &T){
T=NULL;
ElemType e;
cin>>e.key;
while(e.key!=ENDFLAG){
Insert_BSTree(T,e); //循环插入
cin>>e.key;
}
}
//中序遍历
void InOrderTraverse(BSTree T){
if(T){
InOrderTraverse(T->lchild);
cout<<T->data.key<<' ';
InOrderTraverse(T->rchild);
}
}
//查找
BSTree SearchBST(BSTree T,KeyType key){
if((!T)||T->data.key==key) return T; //树空(未找到) 或 已找到
else if(key<T->data.key) SearchBST(T->lchild,key);
else SearchBST(T->rchild,key);
}
int main(){
BSTree T;
cout<<"请输入数据:";
Create_BSTree(T);
cout<<"中序遍历结果为:";
InOrderTraverse(T);
cout<<endl<<"请输入要查找关键字:";
KeyType key;
cin>>key;
BSTree result=SearchBST(T,key);
if(result){
cout<<"找到";
}
else cout<<"未找到";
return 1;
}
运行结果: