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 8Sample Input 2:
8 - - 4 5 0 6 - - 2 3 - 7 - - - -Sample Output 2:
NO 1
题目大意
给你一棵树n个节点的左右孩子情况,让你判断这棵树是不是完全二叉树。
解题思路
用数组模拟建立二叉树就可以了。我为了数组表达的清楚,把每个节点的下标都加了一,一次节点的位置是1-n,这样i节点的左子树就是2*i,右子树就是2*i+1。
接着深搜计算每个节点的下标,得出节点的最大下标,等于n就是满二叉树,否则,就不是。
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
const int MAXN = 50 + 5;
const int MAXM = 100000 + 5;
const int INF = 0x7f7f7f7f;
template <class XSD> inline XSD f_min(XSD a, XSD b) { if (a > b) a = b; return a; }
template <class XSD> inline XSD f_max(XSD a, XSD b) { if (a < b) a = b; return a; }
int n, m;
int max_;
struct NODE{
int pos;
int l, r;
}node[MAXN];
void Dfs(int root, int num){
node[root].pos = num;
max_ = f_max(max_, num);
if(node[root].l!=INF){
Dfs(node[root].l, num*2);
}
if(node[root].r!=INF){
Dfs(node[root].r, num*2+1);
}
}
void Getdata(){
max_ = 0;
char x[3], y[3];
int x_, y_;
bool vis[MAXN];
memset(vis, false, sizeof vis);
for(int i=1; i<=n; i++){
scanf(" %s%s", x, y);
int l1=strlen(x), l2=strlen(y);
if(x[0]!='-'){
if(l1==1) x_ = x[0]-'0' + 1;
else x_ = (x[0]-'0')*10 + x[1]-'0' + 1;
node[i].l = x_;
vis[x_] = true;
}else node[i].l=INF;
if(y[0]!='-'){
if(l2==1) y_ = y[0]-'0' + 1;
else y_ = (y[0]-'0')*10 + y[1]-'0' + 1;
node[i].r = y_;
vis[y_] = true;
}else node[i].r=INF;
}
int root;
for(int i=1; i<=n; i++) if(!vis[i]) root=i;
Dfs(root, 1);
if(max_==n){
for(int i=1; i<=n; i++){
if(node[i].pos==max_){
printf("YES %d\n", i-1);
break;
}
}
}
else printf("NO %d\n", root-1);
}
void Solve(){
for(int i=1; i<=n; i++)
printf("%d %d %d\n", node[i].pos, node[i].l-1, node[i].r-1);
}
int main(){
while(~scanf("%d", &n)){
Getdata();
///Solve();
}
return 0;
}