您的位置:首页 > 其它

求二叉树高度

2012-10-22 00:00 127 查看
#include<iostream>
using namespace std;
typedef struct tree
{
char data;
struct tree *lchild,*rchild;
}bitree;

void creattree(bitree *&T)
{
char data;
cin>>data;
if(data=='#')
T=NULL;
else
{
T=new(bitree);
T->data=data;

creattree(T->lchild);
creattree(T->rchild);
}
}
void preorder(bitree *T)
{
if(T)
{
cout<<T->data<<" ";
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(bitree *T)
{
if(T)
{
inorder(T->lchild);
cout<<T->data<<" ";
inorder(T->rchild);
}
}
void fallorder(bitree *T)
{
if(T)
{
fallorder(T->lchild);
fallorder(T->rchild);
cout<<T->data<<" ";
}
}

int depth(bitree *T)
{
int ldep,rdep;
if(T==NULL)
return 0;
else
{
ldep=depth(T->lchild);
rdep=depth(T->rchild);
return ldep>rdep?ldep+1:rdep+1;

}
}

int sumleaf(bitree *T)
{
int sum=0,n,m;
if(T )
{
if((!T->lchild )&&(!T->rchild ))
sum++;
n=sumleaf(T->lchild);
sum+=n;
m=sumleaf(T->rchild);
sum+=m;
}
return sum;
}

int main()
{
bitree *T=NULL;
creattree(T);
cout<<"pre:";
preorder(T);
cout<<endl;
cout<<"in :";
inorder(T);
cout<<endl;
cout<<"fal:";
fallorder(T);
cout<<endl;
cout<<"the depth:" ;
cout<<depth(T);
cout<<endl;
cout<<sumleaf(T);//根不算
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: