C,无复杂代码,无详细注释,自写,请读者视情参考
思想:
利用层次遍历(使用队列),若能记录上一层最后一个节点,那么这一层最后一个节点减去上一层最后一个节点,就是这一层的宽度。
所需知识:
C,二叉树,层次遍历
途径:
设变量last,记录上一层最后一个节点(对第二层来说,上一层最后一个节点就是根节点)。
举例:
对于第三层,last是第二层最后一个节点,当队列的 font 追上 变量last 的时候,说明第二层已经出列完毕,同时也意味着第三层入列完毕,此时队列的 rear 就是第三层最后一个节点,那么rear - last 就是第三层节点数(也就是宽度),再last = rear,记录第三层最后一个节点,直到层次遍历结束。
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
#define ElemType int
#define OK 1
#define ERROR 0
#define MaxNodeCount 50
typedef int Status;
typedef struct BiTreeNode
{
ElemType data;
struct BiTreeNode* lchild;
struct BiTreeNode* rchild;
}BiTreeNode, * Bitree;
Bitree Queue[MaxNodeCount];
int front = 0, rear = 0, last = 0, lev = 0;
int wid[MaxNodeCount] = { 0 };
Bitree found = NULL;
int fData = 0;
//T 参数为被插入的节点,data 为插入数据,优先左插
void LchildFirstInsert(Bitree& T, int data) {
Bitree P = (BiTreeNode*)malloc(sizeof(BiTreeNode));
P->data = data;
P->lchild = NULL;
P->rchild = NULL;
if (T == NULL) {
T = P;
}
else {
if (T->lchild == NULL) {
T->lchild = P;
}
else {
T->rchild = P;
}
}
}
Status LevelOrder(Bitree& T, Status(*Visit)(Bitree&)) {
if (T == NULL)
{
return ERROR;
}
Bitree p = T;
front = -1; rear = -1; last = 0; lev = 0, wid[0] = 1;
Queue[++rear] = p;
while (front < rear) {
p = Queue[++front];
if (!Visit(p))return OK;
if (p->lchild) {
Queue[++rear] = p->lchild;
}
if (p->rchild)
{
Queue[++rear] = p->rchild;
}
if (front == last)
{
++lev;
wid[lev] = rear - last;
last = rear;
}
}
return OK;
}
Status Find(Bitree& T) {
if (fData == T->data) {
found = T;
return ERROR;
}
return OK;
}
Status PrintData(Bitree& T) {
printf("%d ", T->data);
return OK;
}
Status DoNothing(Bitree& T) {
return OK;
}
Status main() {
Bitree T = NULL;
int n;//有n个结点
int x, y;//二叉树中x为y的父节点。x第一次出现时y为左孩子
LchildFirstInsert(T, 1);
scanf("%d", &n);
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
fData = x;
found = NULL;
LevelOrder(T, Find);
LchildFirstInsert(found, y);
}
LevelOrder(T, DoNothing);
int maxWidth = 0;
for (int i = 0; wid[i]; i++) {
maxWidth = wid[i] > maxWidth ? wid[i] : maxWidth;
}
printf("%d", maxWidth);
}
Description
二叉树的宽度指的是具有节点数目最多的那一层的节点个数。
1
/
2 3
/
4
答案为2, 第二层节点数最多,为2个节点。
输入格式
共n行。
第一行一个整数n,表示有n个结点,编号为1至n。(1<=n<=50)
第二行至第n行,每行有两个整数x和y,表示在二叉树中x为y的父节点。x第一次出现时y为左孩子
输出格式
输出二叉树的直径。
输入样例
5
1 2
1 3
2 4
2 5
输出样例
2
通过层次遍历计算二叉树各层节点数,找到最大宽度。利用C语言实现,记录上一层最后一个节点来确定当前层宽度。

被折叠的 条评论
为什么被折叠?



