王道上也有这样一道题,这里的算法跟书上的不太一样,但测算的结果是正确的,应该没多大问题了。
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef struct BTNode {
int data;
struct BTNode *left, *right;
}BTNode;
typedef int elemtype;
typedef struct
{
BTNode* data;
int level; //用于存储当前结点所在的层
}Queue;
BTNode *creat_bt(){ //按扩展前序建二叉树;
BTNode *t;int x;
scanf("%d",&x);
if (x==0) t=NULL;
else
{ t=(BTNode *)malloc(sizeof(BTNode));
t->data=x;
t->left=creat_bt();
t->right=creat_bt();
}
return t;
}
//非递归算法求二叉树的高度(层次遍历)
void depth_width(BTNode *bt, int *depth, int *width)
{
Queue qu[maxsize]; int front = 0, rear = 0;
BTNode *p;
int k=0;
qu[++rear].data = bt;
qu[rear].level = 1;
while(front != rear)
{
p = qu[++front].data;
k = qu[front].level;
if(p->left != NULL)
{
qu[++rear].data = p->left;
qu[rear].level = k+1;
}
if(p->right != NULL)
{
qu[++rear].data = p->right;
qu[rear].level = k+1;
}
}
*depth = k; //层次遍历结束时,k的值为最后一层的层数,即树的深度
int i = 0, j = 0, max = 0, n = 0; //max表示最大层结点个数,n表示某层的结点总数
while(i<=rear)
{
n = 1;
for(j = i; qu[j+1].level == qu[j].level && j<=rear; j++)
n++;
if(max < n) max = n;
i = i+n;
}
*width = max;
}
void main()
{
BTNode *bt = creat_bt();
int de = 0, wid = 0;
depth_width(bt, &de, &wid);
printf("depth=%d\nwidth=%d\n", de, wid);
}