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
题目大意:
给出有n个结点的二叉树,编号从0~n-1随后n行给出编号为i的左右孩子编号,如果没有则 用 – 替代。
要求判断是否为完全二叉树,并输出根节点。
思路:
由于结点的缺省是可能发生在任一一个地方的(缺省是相对于完全二叉树而言),所以呢,做好还是得到一个层序序列,然后直接判断第一个-1的位置(将没有孩子的结点都赋值为-1),且如果其后有一个是有效值,那么肯定不是完全二叉树。
判断根节点在录入的时候就可以进行准备,使左右孩子都标志为有父结点,最后遍历一下标志数组,没有父结点的就是根结点。
参考代码:
#include<iostream>
#include<vector>
#include<string>
#include<queue>
using namespace std;
struct node{
int l, r;
};
vector<node> t;
vector<int> level, have;
int n, root;
void layer(int v){
queue<int> q;
q.push(v);
while(!q.empty()){
int top = q.front();
q.pop();
level.push_back(top);
if(top == -1) continue;
q.push(t[top].l);
q.push(t[top].r);
}
}
int main(){
scanf("%d", &n);
t.resize(n), have.resize(n);
for(int i = 0; i < n; ++i){
string l , r;
cin >> l >> r;
if(l[0] != '-') t[i].l = stoi(l), have[stoi(l)] = 1;
else t[i].l = -1;
if(r[0] != '-') t[i].r = stoi(r), have[stoi(r)] = 1;
else t[i].r = -1;
}
while(root < n && have[root]) root++;
layer(root);
int leaf;
for(int i = 0; i < level.size(); ++i)
if(level[i] == -1){
leaf = i;
break;
}
for(int i = leaf; i < level.size(); ++i)
if(level[i] != -1){
printf("NO %d", root);
return 0;
}
printf("YES %d", level[leaf - 1]);
return 0;
}