描述如上…
代码如下…(码莫见怪…ε=ε=ε=┏(゜ロ゜;)┛逃
#include <bits/stdc++.h>
using namespace std;
int cnt = 0;
int visit[100];
int add=1;
typedef struct Node
{
char date;
struct Node *leftChild;
struct Node *rightChild;
}*Tree1,treeNode;
void CreateTree(Tree1 *T)//建树
{
char t;
cin>>t;
if(t=='#')
{
*T=NULL;
}
else
{
*T=(Tree1)malloc(sizeof(treeNode));
if(!(*T))
exit(1);
(*T)->date = t;
CreateTree(&((*T)->leftChild));
CreateTree(&((*T)->rightChild));
}
}
void preOrder(Tree1 T) //先序
{
if(T)
{
cout<<T->date<<" ";
preOrder(T->leftChild);
preOrder(T->rightChild);
}
}
void inOrder(Tree1 T) //中序
{
if(T)
{
inOrder(T->leftChild);
cout<<T->date<<" ";
inOrder(T->rightChild);
}
}
void postOrder(Tree1 T)//后序
{
if(T)
{
postOrder(T->leftChild);
postOrder(T->rightChild);
cout<<T->date<<" ";
}
}
int Height(Tree1 T) //深度
{
if(!T)
return 0;
int l = Height(T->leftChild);
int r = Height(T->rightChild);
return max(l,r)+1;
}
int checknum(Tree1 T,char x) //查x次数
{
if(T)
{
if(T->date==x)
{
cnt++;
return cnt;
}
preOrder(T->leftChild);
preOrder(T->rightChild);
return cnt;
}
}
int nodenum(Tree1 T)//结点个数
{
if(!T)
{
return 0;
}
return 1+nodenum(T->leftChild)+nodenum(T->rightChild);
}
int leafnum(Tree1 T)//叶节点数
{
if(!T)
{
return 0;
}
if((!(T->leftChild))&&(!(T->rightChild)))
return 1;
return leafnum(T->leftChild)+leafnum(T->rightChild);
}
void drawtree(Tree1 T) //缩格文本输出
{
if(T)
{
visit[T->date-'A']=add;
add++;
drawtree(T->leftChild);
drawtree(T->rightChild);
add--;
}
}
void drawtree2(Tree1 T) //缩格文本输出
{
if(T)
{
for(int j=1;j<visit[T->date-'A'];j++)
{
cout<<" ";
}
cout<<T->date<<endl;
drawtree2(T->leftChild);
drawtree2(T->rightChild);
}
}
int main()
{
Tree1 tree;
tree=NULL;
char choice;
while(1)
{
cin>>choice;
if(choice=='C')
{
CreateTree(&tree);
cout<<"Created success!"<<endl;
}
else if(choice=='H')
{
cout<<"Height="<<Height(tree)<<"."<<endl;
}
else if(choice=='L')
{
cout<<"Leaf="<<leafnum(tree)<<"."<<endl;
}
else if(choice=='N')
{
cout<<"Nodes="<<nodenum(tree)<<"."<<endl;
}
else if(choice=='1')
{
cout<<"Preorder is:";
preOrder(tree);
cout<<"."<<endl;
}
else if(choice=='2')
{
cout<<"Inorder is:";
inOrder(tree);
cout<<"."<<endl;
}
else if(choice=='3')
{
cout<<"Postorder is:";
postOrder(tree);
cout<<"."<<endl;
}
else if(choice=='F')
{
char a;
cin>>a;
cout<<"The count of "<<a<<" is "<<checknum(tree,a)<<"."<<endl;
}
else if(choice=='P')
{
cout<<"The tree is:"<<endl;
drawtree(tree);
drawtree2(tree);
break;
}
}
return 0;
}