Given a tree, you are supposed to tell if it is a complete binary
tree.nodeInput Specification:ios
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.c++Output Specification:spa
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.code
判斷一顆二叉樹是否是徹底的,只須要判斷可否用大小爲n的堆來表示這棵樹。(樹的大小爲n)
用int nl[21]={-1},nr[21]={-1}
來表示一棵二叉樹。ci
#include <cstdio> #include <string> #include <vector> #include <set> #include <cmath> #include <algorithm> #include <fstream> #include <iostream> #include <limits> #include <map> #include <unordered_set> #include <assert.h> #include <memory.h> using namespace std; #define INF INT_MAX-10000 #define repeat(n) for(int _i=0;_i<n;_i++) // typedef long long ll; int n; #define INPUT cin>>n int nl[21]={-1},nr[21]={-1},heep[21]={1},not_root[21]={0}; bool is_tree(int node,int no) { if(node==-1) return true; if(no>n) return false; heep[no]=node; return is_tree(nl[node],2*no)&&is_tree(nr[node],2*no+1); } int main() { #ifdef _DEBUG fstream cin("input.txt"); #endif while(INPUT) { memset(nl,-1,21*4); memset(nr,-1,21*4); memset(heep,-1,21*4); int t=0; assert(n<21); while(t<n) { int a=0,b=0;string str; if(scanf("%d",&a)) nl[t]=a,not_root[a]=1; if(scanf("%d",&b)) nr[t]=b,not_root[b]=1; assert(a<n);assert(b<n); t++; } int p=0; while(not_root[p]) p++; if(is_tree(p,1)) { cout<<"YES "<<heep[n]<<endl; }else { cout<<"NO "<<p<<endl; } } return 0; }