思路参考链接:http://blog.csdn.net/qinghezhen/article/details/12857717
题目:求二叉树中每层结点数的最大值:
例题:
输出为:
考虑用层次遍历实现:(具体注意点见代码注释)
#include <stdio.h>
#include <stdlib.h>
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(); /* 实现细节忽略 */
int widthOfTheTree( BinTree BT );
int main()
{
int temp = 0;
BinTree BT = CreatBinTree();
temp = widthOfTheTree(BT);
printf("Levelorder:%d",temp); printf("\n");
return 0;
}
//静态建树
BinTree CreatBinTree()
{
BinTree pa = (BinTree)malloc(sizeof(struct TNode));
BinTree pb = (BinTree)malloc(sizeof(struct TNode));
BinTree pc = (BinTree)malloc(sizeof(struct TNode));
BinTree pd = (BinTree)malloc(sizeof(struct TNode));
BinTree pe = (BinTree)malloc(sizeof(struct TNode));
BinTree pf = (BinTree)malloc(sizeof(struct TNode));
BinTree pg = (BinTree)malloc(sizeof(struct TNode));
BinTree ph = (BinTree)malloc(sizeof(struct TNode));
BinTree pi = (BinTree)malloc(sizeof(struct TNode));
pa->Data = 'A';
pb->Data = 'B';
pc->Data = 'C';
pd->Data = 'D';
pe->Data = 'E';
pf->Data = 'F';
pg->Data = 'G';
ph->Data = 'H';
pi->Data = 'I';
pa->Left = pb; pa->Right = pc;
pb->Left = pd; pb->Right = pf;
pc->Left = pg; pc->Right = pi;
pd->Left = NULL; pd->Right = NULL;
pe->Left = NULL; pe->Right = NULL;
pf->Left = pe; pf->Right = NULL;
pg->Left = NULL; pg->Right = ph;
ph->Left = NULL; ph->Right = NULL;
pi->Left = NULL; pi->Right = NULL;
return pa;
}
int widthOfTheTree( BinTree BT )
{
int maxwidth = 0,nextwidth = 0,curwidth=0;
int maxsize = 10;
int front,rear;
BinTree queue[maxsize]; //注意存的是指向结点的指针,而不是结点值;
front = rear = 0;
BinTree temp; //存放临时结点指针;
if(BT != NULL){ //这里必须加if判断,否则PAT编译器老是报段错误,满分25分扣两分
//根结点入队
rear = (rear+1)%maxsize;
queue[rear] = BT;
curwidth++;
//队不空循环
while(front != rear){
while(curwidth != 0){ /*设置curwidth 的目的是为了限制入队的时间点,只要当前层的宽度还没减到0,就一直进队,这样
nextwidth就是记录的是每层的结点数,否则没有curwidth进行控制,则nextwidth只能记录一个结点
的孩子结点数之后,就和maxwidth比较,显然是错的,总的来说,curwidth的设置是为了让nextwidth
记录一层结点的所有孩子结点数才跟maxwidth去比较;建议手工模拟下层次遍历的进出队时间点,会理解
的比较透彻点*/
//队结点出队
front = (front+1)%maxsize;//注意队列出队入队,都是一样的:都是先移动指针,再动队元素,与栈不同,要区分
temp = queue[front];
curwidth--;
//出队的结点的左右结点入队
if(temp->Left){
rear = (rear+1)%maxsize;
queue[rear] = temp->Left;
nextwidth++;
}
if(temp->Right){
rear = (rear+1)%maxsize;
queue[rear] = temp->Right;
nextwidth++;
}
}
if (nextwidth > maxwidth){
maxwidth = nextwidth;
}
curwidth = nextwidth;
nextwidth = 0;
}
}
return maxwidth;
}