输入Result
C ABC##DE#G##F### H L N 1 2 3 F A P
Created success! Height=5. Leaf=3. Nodes=7. Preorder is:A B C D E G F . Inorder is:C B E G D F A . Postorder is:C G E F D B A . The count of A is 1. The tree is: A B C D E G F
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
///结点
typedef struct node ///声明一个变量并且定义
{
char data;
struct node *lchild,*rchild;
} bnode,*btree;
void createTree(btree &T)
{
char ch;
if((ch=getchar())=='#')
{
T=NULL;
}
else
{
T=(bnode*)malloc(sizeof(bnode));
T->data=ch;
createTree(T->lchild);
createTree(T->rchild);
}
}
void preT(btree T)
{
if(T!=NULL)
{
printf("%c ",T->data);
preT(T->lchild);
preT(T->rchild);
}
//else printf(" ");
}
void inorder(btree T)
{
if(T!=NULL)
{
inorder(T->lchild);
printf("%c ",T->data);
inorder(T->rchild);
}
//else printf(" ");
}
void postorder(btree T)
{
if(T!=NULL)
{
postorder(T->lchild);
postorder(T->rchild);
printf("%c ",T->data);
}
//else printf(" ");
}
int depth(btree T)
{
int d;
if(T==NULL)
{
d=0;
}
else
{
int dl=depth(T->lchild);
int dr=depth(T->rchild);
d=1+(dl>dr?dl:dr);
}
return d;
}
int leaf(btree T)
{
if(T== NULL) return 0;///kong shu
else if(T->lchild==NULL&&T->rchild==NULL) return 1;
return leaf(T->lchild)+leaf(T->rchild);
}
int nodes(btree T)
{
if(T==NULL) return 0;
if((T->lchild)==NULL&&(T->rchild==NULL)) return 1;
return 1+nodes(T->lchild)+nodes(T->rchild);
}
int Find(btree T,char ch)
{
if(T==NULL)
{
return 0;
}
else if(T->data==ch)
{
return 1+Find(T->lchild,ch)+Find(T->rchild,ch);
}
return 0;
}
void output(btree T,int l)
{
if(T!=NULL)
{for(int i=1;i<l;i++)
printf(" ");
//if(T==NULL) return ;
//if(T->data=='#') printf(" ");
printf("%c\n",T->data);
output(T->lchild,l+1);
output(T->rchild,l+1);
}
}
int main()
{
char ch;
struct node * Tree;
while(~scanf("%c",&ch))
{
if(ch=='C')
{
getchar();
//getchar();
createTree(Tree);
cout<<"Created success!"<<endl;
}
else if(ch=='H')
{
int h=depth(Tree);
cout<<"Height="<<h<<"."<<endl;
}
else if(ch=='L')
{
cout<<"Leaf="<<leaf(Tree)<<"."<<endl;
//cout<<leaf(Tree);
}
else if(ch=='N')
{
cout<<"Nodes="<<nodes(Tree);
cout<<"."<<endl;
}
else if(ch=='1')///先序遍历
{
cout<<"Preorder is:";
preT(Tree);
cout<<"."<<endl;
}
else if(ch=='2')
{
cout<<"Inorder is:";
inorder(Tree);
cout<<"."<<endl;
}
else if(ch=='3')
{
cout<<"Postorder is:";
postorder(Tree);
cout<<"."<<endl;
}
else if(ch=='F')
{
string s;
cin>>s;
// cout<<"kk"<<kk<<endl;
cout<<"The count of "<<s[0]<<" is "<<Find(Tree,s[0])<<"."<<endl;
}
else if(ch=='P')
{
cout<<"The tree is:"<<endl;
output(Tree,1);
}
}
return 0;
}