#include <iostream>
#include<stdio.h>
using namespace std;
typedef int KeyType;
typedef char InfoType;
#define ENDFLAG -1
typedef struct
{
KeyType key;
InfoType otherinfo;
}ElemType;//结点的数据域类型
typedef struct BSTNode
{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
BSTree SearchBST(BSTree T,KeyType key);
BSTree SearchBST(BSTree T,KeyType key)
{//在二叉排序树T上查找关键字key的记录(结点)
if(!T||key==T->data.key) return T;
else if(key<T->data.key) return SearchBST(T->lchild,key);
else return SearchBST(T->rchild,key);
}
void InsertBST(BSTree &T,ElemType e)//在二叉排序树T上插入值为e的记录
{//BSTree s;
if(!T)//如果T为空,则为T生成新节点
{
T=new BSTNode ;//s=new BSTNode;
T->data=e;//s->data=e;
T->lchild=T->rchild=NULL;//s->lchild=S->rchild=NULL;
//T=s;
}
else if(e.key<T->data.key)
InsertBST(T->lchild, e);//若e的关键字小于T的关键字,则插入到T的左子树
else if(e.key>T->data.key)//若e的关键字大于T的关键字,则插入到T的右子树
InsertBST(T->rchild, e);
}
void CreatBST(BSTree &T)//创建二叉排序树
{
ElemType e;
T=NULL;
cin>>e.key;
while(e.key!=ENDFLAG)
{
InsertBST(T,e);
cin>>e.key;
}
}
void InorderTraverse(BSTree T)//中序遍历二叉排序树,得到有序序列
{
if(T)//若T不空
{
InorderTraverse(T->lchild);//遍历左子树
cout<<T->data.key<<" ";//访问根结点,输出数据域的关键字
InorderTraverse(T->rchild);//遍历右子树
}
}
int main()
{
BSTree T;
KeyType key;
BSTree p;
CreatBST(T);
InorderTraverse(T);
cin>>key;
p=SearchBST(T,key);
if(p)
{
cout<<"查找成功!";
if(p->lchild)
cout<<key<<"的左子节点是"<<p->lchild->data.key<<",";
if(p->rchild)
cout<<key<<"的右子节点是"<<p->rchild->data.key<<",";
cout<<endl;
}
else
cout<<"查找失败!"<<endl;
cout<<endl;
return 0;
}
二叉排序树的创建(插入),中序遍历及查找
最新推荐文章于 2020-11-29 15:56:20 发布