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
结尾无空行
坑点分析:输入的数可能是两位数,所以不能用 char,只能用 string,空节点用 -1 代替
判断是否是完全二叉树的方法:只需要判定最后一个节点的下标是否等于节点的个数,比如此题,画出图以后,最后一个节点的下标是 9,正好 n 也是 9,说明是完全二叉树,(根节点下标是 1),树的经典题目,建议掌握
#include<iostream>
#include<bits/stdc++.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<deque>
#include<unordered_set>
#include<unordered_map>
#include<cctype>
#include<algorithm>
#include<stack>
using namespace std;
vector<int> v[21];
bool flag = true;
int maxIndex = -1;
int last;
void Dfs(int root, int index) {
if (root == -1) {
return;
}
if (maxIndex < index) {
maxIndex = index;
last = root;
}
Dfs(v[root][0], index * 2);
Dfs(v[root][1], index * 2 + 1);
}
int main() {
int n;
cin >> n;
bool vis[n] = {false};
for (int i = 0; i < n; i++) {
string l, r;
cin >> l >> r;
if (l != "-") {
v[i].push_back(stoi(l));
vis[stoi(l)] = true;
} else {
v[i].push_back(-1);
}
if (r != "-") {
v[i].push_back(stoi(r));
vis[stoi(r)] = true;
} else {
v[i].push_back(-1);
}
}
int root;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
root = i;
break;
}
}
Dfs(root, 1);
if (maxIndex == n) {
cout << "YES";
cout << " " << last;
} else {
cout << "NO";
cout << " " << root;
}
}