PAT甲级 A1110
题目详情
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
解题思路
本题建立二叉树,需要判断当出现未满节点得层序后节点中是否存在子树。同时需要判断子树是否合法(例如有右节点无左节点不合法),即可实现
以下为AC代码
#include<algorithm>
#include<iostream>
#include<vector>
#include<cmath>
#include<iomanip>
#include<map>
#include<queue>
#include<string>
using namespace std;
int N;
class node {
public:
int left=-1;
int right=-1;
int isnfull=0;
};
node tree[50];
bool isroot[50];
int judge = 0;
int stoint(string a) {
int sum = 0; int t = 1;
for (int i = a.size() - 1; i >= 0; i--) {
sum += (a[i] - '0') * t;
t = t * 10;
}
return sum;
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) {
string a, b;
cin >> a >> b;
if (a != "-") {
int nums = stoint(a);
tree[i].left = nums;
isroot[nums] = 1;
}
if (b != "-") {
int nums = stoint(b);
tree[i].right = nums;
isroot[nums] = 1;
}
if (a == "-" || b == "-") {
tree[i].isnfull = 1;
}
if (a == "-" && b != "-") {
judge = 1;
}
}
int pos = 0;
for (int i = 0; i < N; i++) {
if (isroot[i] == 0) {
pos = i;
break;
}
}
if (judge == 1) {
cout << "NO"<<" "<<pos << '\n';
return 0;
}
int lastroot = pos;
queue<int> ques;
ques.push(pos);
int lastept = 0;
while (!ques.empty()) {
queue<int> temps;
while (!ques.empty()) {
int nd = ques.front();
lastroot = nd;
ques.pop();
if (lastept == 1) {
if (tree[nd].left != -1|| tree[nd].right != -1) {
judge = 1;
break;
}
}
lastept = tree[nd].isnfull;
if (tree[nd].left != -1) {
temps.push(tree[nd].left);
}
if (tree[nd].right != -1) {
temps.push(tree[nd].right);
}
}
if (judge == 1) {
break;
}
ques = temps;
}
if (judge == 0) {
cout << "YES" <<" "<<lastroot<< '\n';
}
else {
cout << "NO" <<" "<<pos<< '\n';
}
}