二叉排序树的建立,中序遍历,前序遍历,后序遍历,计算总结点数,计算树的深度
#include<iostream.h>
#include<string.h>
typedef struct Node
{
int element;
struct Node * Lchild;
struct Node * Rchild;
}*Tree,TNode;
//二叉排序树的建立
void creatTree(Tree& T,int m)
{
if(T==NULL)
{
T=new TNode;
T->element=m;
T->Lchild=T->Rchild=NULL;
return ;
}
if(m<(T->element)) creatTree(T->Lchild,m);
else creatTree(T->Rchild,m);
}
//前序遍历
void PreOrder(Tree T)
{
if(T)
{
cout<<T->element<<' ';
PreOrder(T->Lchild);
PreOrder(T->Rchild);
}
}
//中序遍历
void InOrder(Tree T)
{
if(T)
{
InOrder(T->Lchild);
cout<<T->element<<' ';
InOrder(T->Rchild);
}
}
//后序遍历
void PostOrder(Tree T)
{
if(T)
{
PostOrder(T->Lchild);
PostOrder(T->Rchild);
cout<<T->element<<' ';
}
}
//计算节点总数
int count(Tree T)
{
if(!T) return 0;
else
{
int m=count(T->Lchild);
int n=count(T->Rchild);
return m+n+1;
}
}
//计算树的深度
int deep(Tree T)
{
if(!T) return 0;
int L=deep(T->Lchild);
int R=deep(T->Rchild);
int max=L>R?L:R;
return max+1;
}
//计算叶子的数量
void leaf(Tree T,int &n)
{
if(T)
{
if(!T->Lchild&&!T->Rchild)
n++;
leaf(T->Lchild,n);
leaf(T->Rchild,n);
}
}
/* 方法2:
int leaf(Tree T)
{
if(!T)
return 0;
else if(!T->Lchild&&!T->Rchild)
return 1;
else return leaf(T->Lchild)+leaf(T->Rchild);
}
*/
int main()
{
Tree root;
root=NULL;
int n,num,nleaf;
cout<<"个数:";
cin>>n;
cout<<"依次输入"<<n<<"个数:"<<endl;
for(int i=0;i<n;i++)
{ cout<<"输入第"<<i+1<<"个数"<<endl;
cin>>num;
creatTree(root,num);
}
cout<<"前序遍历:";
PreOrder(root);
cout<<endl;
cout<<"中序遍历:";
InOrder(root);
cout<<endl;
cout<<"后序遍历";
PostOrder(root);
cout<<endl;
cout<<"count:"<<count(root)<<endl;
cout<<"deep:"<<deep(root)<<endl;
nleaf=0;
leaf(root,nleaf);
cout<<"leaf:"<<nleaf<<endl;
return 0;
}