二叉排序树

#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; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值