采用层次遍历的方法
int width(BiTree T)
{
if(T==NULL) return 0;
else
{
BiTree Q[]; //Q队列,元素为二叉树结点指针
front=1;rear=1;
last=1; //同层最右结点在队列中的位置
t=0,maxw=0; //t记录局部宽度
Q[rear]=T;
while(front<=last)
{
p=Q[front++];
t++; // 同层元素数加一
if(p->lchild!=NULL)
Q[++rear]=p->lchild;
if(p->rchild!=NULL)
Q[++rear]=p->rchild;
if(front>last)
{
last=rear; //last指向下层最右元素
if(t>maxw)
maxw=t;
t=0;
}
}
}
return maxw;
}
高度递归算法
int depth(Bitree T)
{
if(T==NULL)
return 0;
else{
m=depth(T->lchild);
n=depth(T->rchild);
if(m>n)
return m+1;
else
return n+1;
}
}
统计叶子数。
//统计二叉树叶子数量
int Lleaf(Bitree T)
{
if(T==NULL) return 0;
if(T->lchild==NULL&&T->rchild==NULL)
retutn 1;
else return Leaf(T->lchild)+Leaf(T->rchild);
}
复制二叉树
int Copy(BiTree T, BiTree &NewT)
{
if(T==NULL)
{
NewT==NULL;return 0;
}
else
{
NewT= New BiTNode;
NewT->data=T->data;
Copy(T->lchild,NewT->lchild);
Copy(T->rchild,NewT->rchild);
}
}