SearchBST(T, key)
{
if(T为空 || T->data.key==key)
return T;
if(k<T->data.key)
return 在左子树中查找;
else
return 在右子树中查找;
}
BSTree SearchBST(BSTree T, KeyType 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);
}
InsertBST(T, key)
{
if(T为空)
{
T=new BSTNode;
T->key=key;
T->lchild=T->rchild=NULL;
return 1;
}
else if(存在相同关键字的节点)
return 0;
else if(k<T->key)
return 插入到左子树中;
else
return 插入到右子树中;
}
CreateBST(T)
{
T = NULL;
cin<<关键字;
while(关键字!=0)
{
InsertBST(T,关键字);//将关键字插入到T所指向的二叉排序树中
cin<<关键字;
}
}
void CreatBST(BSTree &T){
T = NULL;
cin >> key;
while(key != 0){
InsertBST(T, key);
cin >> key;
}
}
typedef struct{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild, *rchild;
}BSTNode, *BSTree;
ElemType e;
BSTree S, T;
BSTree SearchBST(BSTree T, KeyType 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){
if(!T){
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 InOrderTraverse(BSTree T){
if(T){
InOrderTraverse(T->lchild);
cout << T->data.key << " ";
InOrderTraverse(T->rchild);
}
}
int main(){
cout << "请输入关键字" << endl;
CreatBST(T);
cout << "二叉排序树的中序遍历序列:" << endl;
InOrderTraverse(T);
int n;
cout << "输入要查找的数据:" << endl;
while(scanf("%d",&n) != EOF && n){
if(SearchBST(T, n))
cout << "输出查找的结果:该结点已找到。" << endl;
else
cout << "输出查找的结果:该结点未找到。" << endl;
}
return 0;
}
DeleteBST(T, key)
{
if(T为空)
return False;
else
{
if(key==T->key) //找到关键字等于key的数据元素
return Delete(T);
else if(key<T->key)
return DeleteBST(在结点的左子树中搜索);
else
return DeleteBST(在结点的右子树中搜索);
}
}
原文:https://www.cnblogs.com/zghh/p/12732790.html