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 (<=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 8Sample Input 2:
8 - - 4 5 0 6 - - 2 3 - 7 - - - -Sample Output 2:
NO 1
原题链接:
https://www.patest.cn/contests/pat-a-practise/1110
思路:
树的遍历
满二叉树的特征
CODE:
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>
#define N 22
using namespace std;
typedef struct S
{
int ind;
int ls;
int rs;
int s;
int fa;
int tra;
int fl;
};
S t[N];
int tr;
vector<int> ro;
vector<int> le;
vector<S> trav;
void dfs1(int n,int flo)
{
t[n].fl=flo;
if (t[n].ls!=-1)
{
dfs1(t[n].ls,flo+1);
}
t[n].tra=tr;
tr++;
trav.push_back(t[n]);
if (t[n].rs!=-1)
{
dfs1(t[n].rs,flo+1);
}
return ;
}
bool cmp(S a,S b)
{
if(a.fl==b.fl)
{
return a.tra<b.tra;
}
else
{
return a.fl<b.fl;
}
}
int main()
{
int n;
cin>>n;
for (int i=0;i<n;i++) t[i].fa=-1;
for (int i=0;i<n;i++)
{
t[i].ind=i;
t[i].s=0;
string a,b;
cin>>a>>b;
if (a!="-")
{
t[i].ls=atoi(a.c_str());
t[t[i].ls].fa=i;
t[i].s++;
}
else
{
t[i].ls=-1;
}
if (b!="-")
{
t[i].rs=atoi(b.c_str());
t[t[i].rs].fa=i;
t[i].s++;
}
else
{
t[i].rs=-1;
}
//cout<<t[i].s<<endl;
if (t[i].s!=0)
{
ro.push_back(i);
}
else
{
le.push_back(i);
}
}
int root;
for (int i=0;i<n;i++)
{
if (t[i].fa==-1)
{
root=i;
break;
}
}
tr=0;
dfs1(root,0);
sort(trav.begin(),trav.end(),cmp);
//cout<<trav[n-1].ind<<endl;
int flag=0;
for (int i=0;i<ro.size();i++)
{
if (t[ro[i]].s!=2)
{
if (!(t[ro[i]].ls==trav[n-1].ind))
{
//cout<<ro[i]<<" "<<t[ro[i]].ls<<" "<<t[ro[i]].rs<<endl;
flag=1;
break;
}
}
}
if (flag==0)
{
for (int i=0;i<le.size();i++)
{
if (t[le[i]].fl<(trav[n-1].fl-1))
{
flag=1;
break;
}
else if (t[le[i]].fl==(trav[n-1].fl-1))
{
if (t[le[i]].tra<trav[n-1].tra)
{
flag=1;
break;
}
}
}
}
if (flag==0)
{
cout<<"YES "<<trav[n-1].ind<<endl;
}
else
{
cout<<"NO "<<root<<endl;
}
return 0;
}