#include<iostream> using namespace std; typedef struct ElemType{ int key; }ElemType; typedef struct BSTNode{ ElemType data; BSTNode *lchild,*rchild; }BSTNode,*BSTree; int flag=1; void InsertBST(BSTree &T,ElemType e ) ;//实现细节隐藏 void CreateBST(BSTree &T ) ;//实现细节隐藏 void InOrderTraverse(BSTree &T);//中序遍历,实现细节隐藏 void DeleteBST(BSTree &T,char key) { BSTree p=T;BSTree f=NULL; BSTree q; BSTree s; while(p){ if (p->data.key == key) break; f=p; if (p->data.key> key) p=p->lchild; else p=p->rchild; } if(!p) ; if ((p->lchild)&& (p->rchild)) { q = p; s = p->lchild; while (s->rchild) {q = s; s = s->rchild;} p->data= s->data; if(q!=p) ; else ; delete s; } else{ if(!p->rchild) { q = p; p = p->lchild; } else if(!p->lchild) { q = p; p = p->rchild; } if(!f) ; else if (q==f->lchild) ; else ; delete q; } } int main() { BSTree T; CreateBST(T); int key; cin>>key; DeleteBST(T,key); InOrderTraverse(T); }补全这个代码 使他能够运转
时间: 2024-01-17 19:03:40 浏览: 107
使用include <iostream>时一定要加using namespace std
完整代码如下:
```c++
#include<iostream>
using namespace std;
typedef struct ElemType{
int key;
}ElemType;
typedef struct BSTNode{
ElemType data;
BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
int flag=1;
void InsertBST(BSTree &T,ElemType e ) {
if(!T) {
BSTree 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 CreateBST(BSTree &T ) {
int i=1,n;
cin >> n;
T=NULL;
ElemType e;
while(i<=n){
cin>>e.key;
InsertBST(T, e);
i++;
}
}
void InOrderTraverse(BSTree &T) {
if(T) {
InOrderTraverse(T->lchild);
if(flag){cout<<T->data.key;flag=0;}
else cout<<" "<<T->data.key;
InOrderTraverse(T->rchild);
}
}
void DeleteBST(BSTree &T,char key) {
BSTree p=T;
BSTree f=NULL;
BSTree q;
BSTree s;
while(p){
if (p->data.key == key) break;
f=p;
if (p->data.key> key) p=p->lchild;
else p=p->rchild;
}
if(!p) cout<<"找不到此节点"<<endl;
else if ((p->lchild)&& (p->rchild)) {
q = p;
s = p->lchild;
while (s->rchild) {
q = s;
s = s->rchild;
}
p->data= s->data;
if(q!=p) q->rchild=s->lchild;
else q->lchild=s->lchild;
delete s;
}
else{
if(!p->rchild) { q = p; p = p->lchild; }
else if(!p->lchild) { q = p; p = p->rchild; }
if(!f) T=p;
else if (q==f->lchild) f->lchild=p;
else f->rchild=p;
delete q;
}
}
int main() {
BSTree T;
CreateBST(T);
int key;
cin>>key;
DeleteBST(T,key);
InOrderTraverse(T);
return 0;
}
```
这份代码可以创建一棵二叉搜索树,并支持删除指定节点。其中,`CreateBST` 函数用于创建二叉搜索树,`InsertBST` 函数用于向二叉搜索树中插入节点,`InOrderTraverse` 函数用于中序遍历二叉搜索树并输出节点的值,`DeleteBST` 函数用于删除指定节点。
阅读全文