1110. Complete Binary Tree (25)
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.
原题
判断一颗二叉树是不是完全的,只需要判断能否用大小为n的堆来表示这棵树。(树的大小为n)
用int nl[21]={-1},nr[21]={-1}
来表示一棵二叉树。
#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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。