PAT 1110 Complete Binary Tree
題目連結:
1110 Complete Binary Tree
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
思路:
判斷一個二叉樹是不是完整二叉樹,從根節點開始,依次放入佇列,如果左子樹或者右子樹為空,則記為-1,同時加入佇列。通過層次遍歷,到第一次出隊時為-1時結束,統計這時候已經便利了的節點數,如果等於總的節點數+1(因為包含了剛出隊為-1的節點),那麼則為完整二叉樹。否則不是完整二叉樹。
#include <iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int left,right;
}tree[25];
queue<int> Q;
int in[25];
int root=0,last=-1,num=0;
void bfs(){
Q.push(root);
while(!Q.empty()){
num++;
int front=Q.front();
Q.pop();
if(front!=-1) last=front;
else break;
Q.push(tree[front].left);
Q.push(tree[front].right);
}
}
int main(int argc, char** argv) {
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
string l,r;
cin>>l>>r;
if(l[0]=='-') tree[i].left=-1;
else{
in[stoi(l)]++;
tree[i].left=stoi(l);
}
if(r[0]=='-') tree[i].right=-1;
else{
in[stoi(r)]++;
tree[i].right=stoi(r);
}
}
while(in[root]) root++;
bfs();
if(num-1!=n){
printf("NO %d\n",root);
}else{
printf("YES %d\n",last);
}
return 0;
}