1110. Complete Binary Tree (25)

来源:互联网 发布:悦诗风吟雪耳面霜知乎 编辑:程序博客网 时间:2024/05/17 20:14

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:
97 8- -- -- -0 12 34 5- -- -
Sample Output 1:
YES 8
Sample Input 2:
8- -4 50 6- -2 3- 7- -- -
Sample Output 2:

NO 1

和前面的题目一样,,没什么变化,注意输入用string不用char。

#include <iostream>
#include <cstring>
#include <map>
using namespace std;
const int maxn = 25;
int n, tree[maxn][2];
map<int, int> bst;
void dfs(int root, int idx)
{
if(root == -1)
return ;
int left = tree[root][0], right = tree[root][1];
dfs(left, 2 * idx + 1);
bst[idx] = root;
dfs(right, 2 * idx + 2);
}
int main()
{
string x, y;
scanf("%d", &n);
int sum = 0;
memset(tree, -1, sizeof(tree));
for(int i = 0; i < n; ++i){
cin>>x>>y;
if(x[0] != '-'){
tree[i][0] = atoi(x.c_str());
sum += atoi(x.c_str());
}
if(y[0] != '-'){
tree[i][1] = atoi(y.c_str());
sum += atoi(y.c_str());
}
}
int root = n * (n - 1) / 2 - sum;
dfs(root, 0);
int i;
for(i = 0; i < n; ++i){
if(bst.count(i) == 0){
printf("NO %d", root);
return 0;
}
}
if(i == n)
printf("YES %d", bst[i -  1]);
return 0;
}

0 0
原创粉丝点击