18924 二叉树的宽度
时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: G++;GCC
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 <cstdio>
#include <cstdlib>
#include <iostream>
#include <malloc.h>
#include <queue>
using namespace std;
int n,level[55];
struct node
{
int parent;//父结点
int lchild;//左孩子
int rchild;//右孩子
} tree[55];
void CreatTree(int fu,int zi)
{
tree[zi].parent=fu;//记录孩子结点的父结点,相当于一个前驱,可用来查找根结点
if(!tree[fu].lchild)
tree[fu].lchild=zi;
else
tree[fu].rchild=zi;
}
void kuandu(int root,int a)
{
level[a]++;//数组level用于记录每一层的个数
//cout << a << ' '<< level[a] <<endl;
int Root;
if(tree[root].lchild)
{
Root=tree[root].lchild;
kuandu(Root,a+1);
}
if(tree[root].rchild)
{
Root=tree[root].rchild;
kuandu(Root,a+1);
}
}
int main()
{
int i,x,y,root;
int MAX=0;
cin >> n;
for(i=1;i<n;i++)
{
cin >> x >> y;
CreatTree(x,y);
}
for(i=1;i<=n;i++)
{
if(tree[i].parent==0)
{
root=i;
break;
}
}
kuandu(root,1);//从根结点、第一层开始
for(i=1;i<55;i++)
{
MAX=max(level[i],MAX);
}
cout << MAX;
return 0;
}