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 8Sample 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;
}
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree (25)
- 1110. Complete Binary Tree
- 1110. Complete Binary Tree
- 1110. Complete Binary Tree
- PAT-Advanced 1110. Complete Binary Tree (25)
- SQL Server 2008 查询表字段相关属性
- CDH调优
- Hbase原理、基本概念、基本架构
- 一个模块
- Leetcode: LetterCombinationsofaPhoneNumber 根据手机按键,给出所有可能的字符串
- 1110. Complete Binary Tree (25)
- 社交类APP动态详情代码通用模板
- linux系统之_中断的前世今生
- bzoj4527
- 初识jazz(IBM)
- photoshop制作圆形渐变边框教程
- EvaluateReversePolishNotation 逆波兰表达式
- Similarity Search in High Dimension via Hashing LSH 原始算法详解
- linux SVN服务器搭建并使用