1110. Complete Binary Tree (25)完全二叉树

来源:互联网 发布:网络服务器托管 编辑:程序博客网 时间:2024/06/05 00:14


Given a tree, you are supposed to tell if it is a complete binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=20) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a “-” will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each case, print in one line “YES” and the index of the last node if the tree is a complete binary tree, or “NO” and the index of the root if not. There must be exactly one space separating the word and the number.

Sample Input 1:
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -

Sample Output 1:
YES 8

Sample Input 2:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -

Sample Output 2:
NO 1

#include<iostream>#include<queue>#include<cstring>#include<cstdio>using namespace std;struct node{int num,left,right;};struct node N[100];int n;int isroot[25];int vis[25];int total=1;int str_int(char a[]){    if (a[0]=='-')        return -1;    else    {        int sum=0;        for (int i=0;i<strlen(a);i++)            sum=sum*10+a[i]-'0';        return sum;    }}int check(){    for (int i=0;i<n;i++)    {        if (vis[i]==0)            return 0;    }    return 1;}void bfs(int root){    queue<int> que;    que.push(root);    int endx=root;    while(!que.empty())    {        int num=que.front();        que.pop();        if (N[num].left==-1)        {            if (total==n)            {                printf("YES %d",endx);                return ;            }            else            {                printf("NO %d",root);                return ;            }        }        else        {            que.push(N[num].left);            endx=N[num].left;            total++;        }        if (N[num].right==-1)        {            if (total==n)            {                printf("YES %d",endx);                return ;            }            else            {                printf("NO %d",root);                return ;            }        }        else        {            que.push(N[num].right);            endx=N[num].right;            total++;        }    }}int main(){   int root;   char a[3],b[3];   cin>>n;   for (int i=0;i<n;i++)   {       cin>>a>>b;       int aa=str_int(a);       int bb=str_int(b);       isroot[aa]=isroot[bb]=1;       N[i].num=i;       N[i].left=aa;       N[i].right=bb;   }   for (int i=0;i<n;i++)   {       if(isroot[i]==0)       {           root=i;           break;       }   }   bfs(root);    return 0;}
阅读全文
1 0
原创粉丝点击