http://cdn.ac.nbutoj.com/Problem/view.xhtml?id=1186

本文详细介绍了如何解决计算二叉树宽度的问题,通过给出的样例输入和输出,帮助理解并实现二叉树宽度的计算算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 问题描述
  • It's an easy problem. I will give you a binary tree. You just need to tell me the width of the binary tree.
    The width of a binary tree means the maximum number of nodes in a same level.


    For example, the width of binary tree above is 3.

  • 输入
  • The first line is an integer T, means the number of cases.
    Then follow T cases.
    For each case, the first line is an integer N, means the number of nodes. (1 <= N <= 10)
    Then follow N lines. Each line contains 3 integers P A B; indicate the number of this node and its two children node. If the node doesn’t have left child or right child, then replace it by -1.
    You can assume the root is 1.
  • 输出
  • For each case, output the width.
  • 样例输入
  • 1
    6
    4 -1 -1
    2 4 5
    5 -1 -1
    1 2 3
    6 -1 -1
    3 -1 6
    
  • 样例输出
  • 3
    AC代码:
    #include<iostream>
    #include<string.h>
    #include<string>
    #include<algorithm>
    #include<cstdio>
    #define N 20
    using namespace std;
    typedef struct 
    {
    	int to;
    	int next;
    }Node;
    Node s[3*N];
    int lev[N];
    int head[N];
    int res;
    void init()
    {
    	res=0;
    	memset(lev,0,sizeof(lev));
    	memset(head,-1,sizeof(head));
    
     }
    void add(int a,int b)
    {
    	s[res].to=b;
    	s[res].next=head[a];
    	head[a]=res++;
    }
    void dfs(int cur,int now)
    {
    	 lev[cur]++;
    	 if(head[now]==-1) return;
    	 for(int i=head[now];i!=-1;i=s[i].next)  dfs(cur+1,s[i].to);
    }
    int main()
    {
    	int T;
        scanf("%d",&T);
    	while(T--)
    	{
    		int n;
    		init();
    		scanf("%d",&n);
    		for(int i=0;i!=n;++i)
    		{
    			int a,b,c;
    			scanf("%d%d%d",&a,&b,&c);
    			if(b!=-1) add(a,b);
    			if(c!=-1) add(a,c);
    		}
    		dfs(0,1);
    		printf("%d\n",*max_element(lev,lev+n));
    	}return 0;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值