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,左孩子结点的编号为2,有孩子结点的编号为3,以此类推,最大编号maxn与节点个数n进行比较,如果两者相等,则此树是完全二叉树,反之则不是。
参考代码(来自别处)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct node {
int left, right;
};
vector<node>tree;
int maxn = 0, ans = 0;
void bfs(int vec,int index) {
if (index > maxn) {
maxn= index;
ans = vec;
}
if (tree[vec].left != -1)bfs(tree[vec].left, 2 * index);
if (tree[vec].right != -1)bfs(tree[vec].right, 2 * index+1);
}
int main()
{
int n, root=0;
scanf_s("%d", &n);
vector<int>v;
v.resize(n, -1);
string l, r;
tree.resize(n);
getchar();
for (int i = 0; i < n; i++) {
cin >> l >> r;
if (l == "-")tree[i].left = -1;
else {
tree[i].left = stoi(l);
v[stoi(l)] = 1;
}
if (r == "-")tree[i].right = -1;
else {
tree[i].right = stoi(r);
v[stoi(r)] = 1;
}
}
while (v[root]!=-1) { root++; }
bfs(root, 1);
if (maxn== n)cout << "YES" << " " << ans;
else cout << "NO" << " " << root;
return 0;
}