Description
二叉树的宽度指的是具有节点数目最多的那一层的节点个数。 1 / \ 2 3 / 4 答案为2, 第二层节点数最多,为2个节点。
输入格式
共n行。 第一行一个整数n,表示有n个结点,编号为1至n,结点1为树根。(1<=n<=50) 第二行至第n行,每行有两个整数x和y,表示在二叉树中x为y的父节点。x第一次出现时y为左孩子
输出格式
输出二叉树的宽度。
输入样例
5 1 2 1 3 2 4 2 5
输出样例
2
用队列来写,详见注释。
为了方便理解,随手画了个图,轻喷。
#include <iostream>
#include <queue>
using namespace std;
typedef struct tree//构建二叉树的结构体
{
int lchild = 0;
int rchild = 0;
}tree;
int main()
{
int n;
cin >> n;
tree T[105];//创建一个结构体数组存储二叉树的结点
for (int i = 1; i <= n-1; i++)//少一个根结
{
int x, y;
cin >> x >> y;
if (!T[x].lchild)//如果左孩子为空则存入左孩子
{
T[x].lchild = y;
}
else
{
T[x].rchild = y;//反之存入右孩子
}
}
int ans = 1;//最小的宽度也有1
queue<int>q;//创建队列
q.push(1);//入队根节点
while (q.size())
{
int len = q.size();//宽度就为队列的长度
ans = max(ans, len);//更新答案
for (int i = 1; i <= len; i++)
{
int t = q.front();//t就是父节点
q.pop();//弹出父节点,接着遍历子节点个数
if (T[t].lchild)//如果有左孩子,则入队
{
q.push(T[t].lchild);
}
if (T[t].rchild)//如果有右孩子也入队
{
q.push(T[t].rchild);
}
}
}
cout << ans << endl;
return 0;
}