原题目:
原题链接:https://www.patest.cn/contests/pat-a-practise/1110
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个节点,并告知每个节点的左右节点,若是‘-’表示节点为空。判断是否为完全二叉树。若是,输出YES和最后一个节点的值。若不是,输出NO和根节点的值。
解题报告
读入,建树,并用visit标记是否为子节点。
做的时候碰到个坑,没注意到节点数范围,单纯认为0-9,用char读入,结果出问题。
代码
/*
* Problem: 1110. Complete Binary Tree (25)
* Author: HQ
* Time: 2018-03-10
* State: Done
* Memo: 完全二叉树的建立及检验。
*/
#include "iostream"
#include "string"
#include "vector"
using namespace std;
string node[20 + 2][2];
bool visit[20 + 2] = { false };
int tree[20 + 2];
bool flag = true;
int N;
void makeTree(int pos, int x) {
if (pos > N || x >= N) {
return;
}
tree[pos] = x;
if (flag && node[x][0][0] != '-')
makeTree(pos * 2, stoi(node[x][0]));
if (flag && node[x][1][0] != '-')
makeTree(pos * 2 + 1, stoi(node[x][1]));
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) {
cin>>node[i][0]>>node[i][1];
if (node[i][0][0] != '-') {
visit[stoi(node[i][0])] = true;
}
if (node[i][1][0] != '-') {
visit[stoi(node[i][1])] = true;
}
}
fill(tree, tree+N+1, -1);
int i;
for (i = 0; i < N; i++) {
if (!visit[i])
break;
}
makeTree(1, i);
for(int j = 1; j <= N; j++)
if (tree[j] == -1) {
printf("NO %d\n", i);
flag = false;
break;
}
if(flag)
printf("YES %d\n", tree[N]);
system("pause");
}