实验四:18924 二叉树的宽度

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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值