4932: 树查找
Time Limit: 1 Sec Memory Limit: 32 MB
Submit: 26 Solved: 16
[Submit][Status][Web Board]Description
有一棵树,输出某一深度的所有节点,有则输出这些节点,无则输出EMPTY。该树是完全二叉树。
Input
输入有多组数据。
每组输入一个n(1<=n<=1000),然后将树中的这n个节点依次输入,再输入一个d代表深度。
Output
输出该树中第d层得所有节点,节点间用空格隔开,最后一个节点后没有空格。
Sample Input
5 1 2 3 4 5 7 7 1 2 3 4 5 6 7 2 0
Sample Output
EMPTY 2 3
HINT
Source
需要知道完全二叉树第x层第一个节点的编号是pow(2,x-1),第x层的节点个数=pow(2,x-1)。
#include <cstdio>
#include <cstdlib>
#include <iostream>
#define mem(a) memset(a,0,sizeof(a))
const int maxn = 1e3+10;
using namespace std;
int a[maxn];
int main()
{
int n,d;
while(cin>>n && n)
{
mem(a);
for(int i = 1;i <= n;i++)
cin>>a[i];
cin>>d;
int start = pow(2,d-1);//d层起始节点
if(start > n)
puts("EMPTY");
else
{
int len = start * 2 - 1 ;//d层节点个数
if(len > n)
len = n;
for(int i = start;i <= len;i++)
{
if(i != start)
cout<<" ";
cout<<a[i];
}
puts("");
}
}
return 0;
}