树的度即为其孩子节点的个数,在储存树的二叉树中,节点左孩子为其第一个孩子节点,右节点为其兄弟节点,则要求节点的度,就要先找其左节点(第一个孩子),置计数器为1,然后往右节点遍历,计数器累加,最终找到计数器最大即为树的度;
如果根节点的右节点不为空,则不满足二叉树储存普通树的性质(因为根节点没有兄弟结点)
int mx=0;
void count(tree *p,int n)
{
if(p==NULL)
return ;
else
{
count(p->r ,n+1);
count(p->l ,1);//左为其第一个孩子节点,从 1开始计算
}
mx=n>mx?n:mx;
}
count(t,0);
完整代码:
#include<iostream>
using namespace std;
typedef struct Tree
{
char data;
struct Tree *l;
struct Tree *r;
}tree;
int mx=0;
void creat(tree *&p)
{
char x;
cin>>x;
if(x=='#')return;
p=new tree;
p->data =x;p->l =NULL;p->r =NULL;
creat(p->l );
creat(p->r );
}
void count(tree *p,int n)
{
if(p==NULL)
return ;
else
{
count(p->r ,n+1);
count(p->l ,1);//左为其第一个孩子节点,从 1开始计算
}
mx=n>mx?n:mx;
}
int main()
{
tree *t;
creat(t);
if(t->r ==NULL)
{
count(t,0);
cout<<mx;
}
else cout<<"ERROR";
return 0;
}