二叉排序树实现

由{4,9,0,1,8,6,3,5,2,7}创建一个二叉排序树

 

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
#define ElemType int
typedef struct BSTNode{
    ElemType data;
    struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
void BSTInsert(BSTree &T,ElemType key){
    if(T==NULL){
        T=(BSTree)malloc(sizeof(BSTNode));
        T->data=key;
        T->lchild=NULL;
        T->rchild=NULL;
    }
    if(key==T->data){
    }//判断树中是否存在相同关键字的节点
    if(key<T->data){
        BSTInsert(T->lchild,key);
    }
    if(key>T->data){
        BSTInsert(T->rchild,key);
    }
}//二叉排序树的插入
void CreatBST(BSTree &T,ElemType str[MAXSIZE],int n){
    T=NULL;
    for(int i=0;i<n;i++){
        BSTInsert(T,str[i]);
    }
}//创建二叉排序树
BSTree BSTSearch(BSTree &T,ElemType key){
    BSTree bst;
    bst=T;
    while(bst!=NULL&&bst->data!=key){
        if(key<bst->data){bst=bst->lchild;}
        else {bst=bst->rchild;}
    }
    return bst;
}//二叉排序树非递归查找
BSTree BSTSearch1(BSTree &T,ElemType key){
    if(T->data==key){
        return T;
    }
    if(T->data>key){
        return BSTSearch1(T->lchild,key);
    }
    if(T->data<key){
        return BSTSearch1(T->rchild,key);
    }
}//二叉排序树递归查找
void visit(BSTree &T){
    if(T!=NULL){
        printf("%d ",T->data);
    }
}
void InOrder(BSTree &T){
    if(T){
        InOrder(T->lchild);
        visit(T);
        InOrder(T->rchild);
    }
}
int main(){
    BSTree T;
    BSTree bt;
    ElemType str[MAXSIZE]={4,9,0,1,8,6,3,5,2,7};
    CreatBST(T,str,10);
    printf("中序遍历二叉排序树:");
    InOrder(T);
    printf("\n");
    bt=BSTSearch1(T,8);
    printf("查询到的节点:%d",bt->data);
}

 

posted on 2019-08-07 21:37  一仟零一夜丶  阅读(483)  评论(0)    收藏  举报