NOJ [1186] Get the Width

  • 问题描述
  • 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.

    其实,方法很多,这里我用的是搜索
    //一个结构体来存点,成员有当前rank,左二子,右儿子
    //输入完以后,sort排序,从根节点开始,依次去存好每个节点的等级,
    
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    struct Node
    {
      int left,right;
    }node[25];
    int rank[25];
    bool lp[25],rp[25];
    int lay,alllay;
    void search_rank(int p)
    {
      if(node[p].left!=-1 && lp[p])  //有左儿子
      {
        rank[lay]++;
        int l=node[p].left;
    	lp[p]=false;
    	lay++;
    	alllay++;
    	//printf("递归%d的左子树节点%d ,当前第%d层有节点%d个\n",p,l,lay-1,rank[lay-1]);
        search_rank(l);
      }
      if(node[p].right!=-1 && rp[p])
      {
    
        rank[lay]++;
    	int r=node[p].right;
    	rp[p]=false;
    	lay++;
    	alllay++;
    	//printf("递归%d的右子树节点%d ,当前第%d层有节点%d个\n",p,r,lay-1,rank[lay-1]);
        search_rank(r);
      }
      lay--;
      return ;
    }
    int cmp(const int a,const int b)
    {
      return a>b;
    }
    int main()
    {
      int T,n,i,j;
      int p,pl,pr;
      while(~scanf("%d",&T))
      {
        while(T--)
        {
          scanf("%d",&n);
          memset(rank,0,sizeof(rank));
          memset(lp,true,sizeof(lp));
          memset(rp,true,sizeof(rp));
          for(i=1;i<=n;i++)
          {
            scanf("%d%d%d",&p,&pl,&pr);
            node[p].left=pl;
            node[p].right=pr;
          }
          rank[1]=1;
          alllay=1;
          lay=2;
          search_rank(1);
          sort(rank+1,rank+alllay+1,cmp);
            printf("%d\n",rank[1]);
        }
      }
      return 0;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值