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 8
Sample Input 2:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
Sample Output 2:
NO 1
判断是否为完全树,如果是的话,请输出yes和最后一个节点的值,如果不是,输出no和根植,用了两种方法,均可ac,一种是dfs,一种是层次遍历
#include<iostream>
#include<string>
#include<vector>
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int lchild,rchild;
};
struct node a[25];
int f1=0,f2=0;
int cnt;
void level(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
cnt = q.front();
q.pop();
if(a[cnt].lchild!=-1){
if(f1==1) f2 = 1;
q.push(a[cnt].lchild);
}else{
f1 = 1;
}
if(a[cnt].rchild!=-1){
if(f1==1) f2 =1;
q.push(a[cnt].rchild);
}else{
f1 = 1;
}
}
}
int main(){
int n;
vector<int> book(25,0);
cin >> n;
for(int i = 0;i < n;i++){
string l,r;
cin >> l >> r;
if(l=="-"){
a[i].lchild = -1;
}else{
a[i].lchild = stoi(l);
book[stoi(l)] = 1;
}
if(r=="-"){
a[i].rchild = -1;
}else{
a[i].rchild = stoi(r);
book[stoi(r)] = 1;
}
}
int root=0;
while(book[root] != 0){
root++;
}
level(root);
if(f2==0){
cout << "YES" << " " << cnt << endl;
}else{
cout << "NO" << " " << root << endl;
}
}
#include<iostream>
#include<string>
#include<vector>
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int lchild,rchild;
};
struct node a[500];
int ans = -1;
int r;
void dfs(int root,int cnt){
if(cnt > ans){
ans = cnt;
r = root;
}
if(a[root].lchild != -1){
dfs(a[root].lchild,cnt*2);
}
if(a[root].rchild != -1){
dfs(a[root].rchild,cnt*2+1);
}
}
int main(){
int n;
vector<int> book(500,0);
cin >> n;
for(int i = 0;i < n;i++){
string l,r;
cin >> l >> r;
if(l=="-"){
a[i].lchild = -1;
}else{
a[i].lchild = stoi(l);
book[stoi(l)] = 1;
}
if(r=="-"){
a[i].rchild = -1;
}else{
a[i].rchild = stoi(r);
book[stoi(r)] = 1;
}
}
int root=0;
while(book[root] != 0){
root++;
}
dfs(root,1);
if(ans==n){
cout << "YES" << " " << r << endl;
}else{
cout << "NO" << " " << root << endl;
}
}