1110 Complete Binary Tree (25 分)
作者:互联网
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 (≤) 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<bits/stdc++.h> using namespace std; const int maxn=1010; #define inf 0x3fffffff struct node{ int lchild=-1; int rchild=-1; }node[maxn]; int dex=1; int flag[maxn]; int maxdex=-1; int ans=-1; void dfs(int root,int index){ if(index>maxdex){ maxdex=index; ans=root; } if(node[root].lchild!=-1){ dfs(node[root].lchild,index*2); } if(node[root].rchild!=-1){ dfs(node[root].rchild,index*2+1); } } int main(){ int n; scanf("%d",&n); // char a,b; string a,b; for(int i=0;i<n;i++){ cin>>a>>b;//a和b可能是两位数,故不能用char存储 if(a=="-"){ node[i].lchild=-1; } else{ int sum=0; for(int j=0;j<a.length();j++){ sum=sum*10+(a[j]-'0'); } node[i].lchild=sum; flag[node[i].lchild]=1; } if(b=="-"){ node[i].rchild=-1; } else{ int sum=0; for(int j=0;j<b.length();j++){ sum=sum*10+(b[j]-'0'); } node[i].rchild=sum; flag[node[i].rchild]=1; } } int root; for(int i=0;i<n;i++){ if(flag[i]!=1){ root=i; break; } } dfs(root,1); if(maxdex>n){ printf("NO %d\n",root); } else{ printf("YES %d\n",ans); } return 0; }
标签:node,index,Complete,int,tree,Tree,1110,root,lchild 来源: https://www.cnblogs.com/dreamzj/p/14443471.html