#include<iostream>
using namespace std;
typedef struct node
{
struct node *lchild;
struct node *rchild;
int key;
}BiTreeNode, *BiTree;
int BSTSearch(BiTree bt, int K, BiTree &p, BiTree &f){
// 在根为 bt 的二叉排序树上查找键值等于 K 的记录
// 查找成功 , 用指针 p 指向目标 ;f 指向目标的双亲 ,f 初值为 NULL
p=bt;
while(p){
if(K<p->key){
f=p;
p=p->lchild;
} // 左子树上继续找
else if(K>p->key) {
f=p;
p=p->rchild;
} // 右子树上继续找
else return 1; // 查找成功
} //end while
return 0; // 查找失败
}
void CreateBST(BiTree &bt){ //建立二叉排序树
BiTree f=NULL;
BiTree p=NULL;
int R;
cout<<"一次输入元素,-1为结束符:"<<endl;
for(cin>>R;R!=-1;cin>>R){
if(!BSTSearch(bt,R,p,f)){ //未找到R.key
BiTree S=new BiTreeNode;
S->key=R;
S->lchild=S->rchild=NULL;
if(!f) bt=S; //二叉排序树中的第一个结点
else if(S->key<f->key) f->lchild=S;
else f->rchild=S;
} //end if
else cout<<"该结点已经存在!"<<endl;
} //for
} //end CreateBST
void midorder(BiTree T)//中序遍历非递归
{
if(T)
{
midorder(T->lchild);
cout<<T->key<<" ";
midorder(T->rchild);
}
}
int main(){
BiTree BT=NULL;
CreateBST(BT);
cout<<"中序遍历二叉排序树的结果为(有序序列):"<<endl;
midorder(BT);
return 0;
}
二叉排序树
最新推荐文章于 2022-11-07 20:21:25 发布