【数据结构作业六b】建立一个二叉排序树,根据给定的定值对其实施查找

#include <iostream>
using namespace std;
typedef int KeyType;
typedef struct{
	KeyType key;
}ElemType;
typedef struct BSTNode{
	ElemType data;
	struct BSTNode *lchild,*rchild; 
}BSTNode,*BSTree; 
int SearchBST(BSTree T,KeyType key) {
	if((!T)||T->data.key==key) return T->data.key;
	else if(key<T->data.key) return SearchBST(T->lchild,key);
	else return SearchBST(T->rchild,key);
}
void InsertBST(BSTree &T,ElemType e){
	if(!T)
	{ 
	    BSTree S; 
		S=new BSTNode;
		S->data=e;
		S->lchild=S->rchild=NULL;
		T=S;
	}
	else if(e.key<T->data.key)
	  InsertBST(T->lchild,e);
	else if(e.key>T->data.key)
   	  InsertBST(T->rchild,e);
}
void CreatBST(BSTree &T){
	ElemType e;
	T=NULL;
	cin>>e.key;
	while(e.key!=0){
		InsertBST(T,e);
		cin>>e.key;
	}
} 
int main(){
	BSTree T;
	int m,n;
	cout<<"请输入二叉排序树的元素!\n";
	CreatBST(T);
	cout<<"请输入要查找的元素:\n";
	cin>>m;
	n=SearchBST(T,m);
	cout<<"查找结果为:\n";
	cout<<n;
}

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/tf1997/article/details/78660024
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞