#include<iostream> using namespace std; typedef struct ElemType{ int key; }ElemType; int flag=1; typedef struct BSTNode{ ElemType data; BSTNode *lchild,*rchild; }BSTNode,*BSTree; void InsertBST(BSTree &T,ElemType e ) { if(!T) { BSTree S = new BSTNode; S->data =e; S->lchild = S->rchild = NULL; ; } else if (e.key< T->data.key) ; else if (e.key> T->data.key) ; } 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); } } int main() { BSTree T; CreateBST(T); InOrderTraverse(T); return 0; }补全这个代码 使他能够运转
时间: 2024-01-15 14:02:56 浏览: 97
完整代码如下:
```c++
#include<iostream>
using namespace std;
typedef struct ElemType{
int key;
}ElemType;
int flag=1;
typedef struct BSTNode{
ElemType data;
BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
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);
}
}
int main() {
BSTree T;
CreateBST(T);
InOrderTraverse(T);
return 0;
}
```
这份代码可以创建一棵二叉搜索树,并按照中序遍历的顺序输出树中节点的值。其中,`CreateBST` 函数用于创建二叉搜索树,`InsertBST` 函数用于向二叉搜索树中插入节点,`InOrderTraverse` 函数用于中序遍历二叉搜索树并输出节点的值。
阅读全文