#include <iostream>
using namespace std;
struct BiTree
{
char data ;
BiTree *left ;
BiTree *right ;
};
BiTree *CreateBiTree()
{
BiTree *S[100],*b,*p;
int i=0,k,l=0,top=0;
char str[100] ;
char ch;
b=NULL;
while((ch=cin.get())!='#')
str[l++]=ch;
str[l]='\0';
while(str[i])
{
switch(str[i])
{
case '(' :S[++top]=p; k=1; break ;
case ')' :top--; break ;
case ',' : k=2; break ;
default :
{
p=new BiTree ;
p->data=str[i];
p->left=NULL;
p->right=NULL ;
if(b==NULL)
b=p;
else
{
switch(k)
{
case 1:S[top]->left=p; break;
case 2:S[top]->right=p; break;
}
}
}
}
i++;
}cout<<"已为您成功录入二叉树!"<<endl;
return b ;
}
void Inorder(BiTree *root)
{
if (root!=NULL)
{
Inorder(root->left );
cout<<root->data;
Inorder(root->right );
}
}
void preorder(BiTree *root)
{ if (root!=NULL)
{
cout<<root->data;
preorder(root->left);
preorder(root->right);
}
}
void lateorder(BiTree *root)
{
if (root!=NULL)
{
lateorder(root->left);
lateorder(root->right);
cout<<root->data;
}
}
void leftorder(BiTree *p)
{
BiTree *qu[100];
int front=0,rear=0;
if(p!=NULL)
cout<<p->data;
rear++;
qu[rear]=p;
while(rear!=front)
{
front=(front+1)%100;
p=qu[front];
if(p->left!=NULL)
{
cout<<p->left->data;
rear=(rear+1)%100;
qu[rear]=p->left;
}
if(p->right!=NULL)
{
cout<<p->right->data;
rear=(rear+1)%100;
qu[rear]=p->right;
}
}
}
int max(int a,int b)
{
return a>b?a:b;
}
int NodeCount ( BiTree *b )
{ int L,R;
if ( b==NULL ) return 0;
L = NodeCount ( b->left );
R = NodeCount ( b->right );
return 1+L+R;
}
int LeafCount ( BiTree *b )
{ int L,R;
if ( b==NULL ) return 0;
if ( b->left==NULL && b->right==NULL)
return 1;
L = LeafCount ( b->left );
R = LeafCount ( b->right );
return L + R;
}
int max1(int a,int b)
{
return a>b?a:b;
}
int Depth ( BiTree *b )
{int L,R;
if ( b==NULL ) return 0;
L=Depth ( b->left );
R=Depth ( b->right );
return 1+max1(L,R);
}
int main()
{
cout<<"欢迎进入:"<<endl;
BiTree *T;
cout<<"请先将您要进行操作的二叉树以广义表的形式录入,以'#'结束输入(例如:A(B,C(,E))#):"<<endl;
T=CreateBiTree( );
int m=100;
char flag;
while(m)
{
cout<<"请选择操作: ";
cin>>flag;
switch(flag)
{
case '0': cout<<"节点个数为:"<<NodeCount(T)<<endl;break;
case '1': cout<<"叶子节点数为:"<<LeafCount(T)<<endl;break;
case '2': cout<<"树的深度为:"<<Depth(T)<<endl;break;
case '3': cout<<"先序遍历:"<<endl;preorder(T);break;
case '4': cout<<"中序遍历:"<<endl;Inorder(T) ;break;
case '5': cout<<"后序遍历:"<<endl;lateorder(T);break;
case '6': cout<<"层次遍历:"<<endl;leftorder(T);break;
case '7': m=1;break;
}
m--;
}
return 0;
}
这个代码就可以,我运行过了,你可以试试
追问你编写的这个程序,符合我问题补充的四点要求吗?你上机运行了吗?没出错误吗?