关键字:求完全二叉树的第h层的结点,跟层数有关的公式的运用
题目描述
有一棵树,输出某一深度的所有节点,有则输出这些节点,无则输出EMPTY。该树是完全二叉树。
输入描述:
输入有多组数据。
每组输入一个n(1<=n<=1000),然后将树中的这n个节点依次输入,再输入一个d代表深度。
输出描述:
输出该树中第d层得所有节点,节点间用空格隔开,最后一个节点后没有空格。
示例1
输入
4
1 2 3 4
2
输出
2 3
代码:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
const int maxn = 1010;
int main(){
// freopen("a.txt", "r", stdin);
//将所有的数字存放到一个数组中,根据公式求出第h层的起始位置(2^(h-1))和终止位置(2^h - 1),读出这些数字即可
int n, h;
int a[maxn];
int start, end;
while(cin >> n){
for(int i = 1; i <= n; ++i){
cin >> a[i];
}
cin >> h;
start = pow(2, h - 1);
end = pow(2, h) - 1;
if(start > n) cout << "EMPTY";
else{
for(int i = start; i <= end; ++i){
cout << a[i];
if(i != end) cout << " ";
}
}
cout <<endl;
}
return 0;
}