题目链接
A 树查找
- 因为是完全二叉树,双亲与孩子结点之间的编号存在数学关系,所以就很简单啦。
- 先存储全部结点,然后找到第 d 层的所有结点,输出即可。参考代码如下。
#include<iostream>
#include<algorithm>
const int maxn = 1010;
using namespace std;
int BT[maxn];
int main() {
int n, d;
while (cin >> n && n) {
for (int i = 1; i <= n; i++)
cin >> BT[i];
cin >> d;
int id = 1;
for (int i = 1; i < d; i++)
id *= 2;
if (id > n)
cout << "EMPTY" << endl;
else {
int t = min(2 * id, n);
while (id < t - 1)
cout << BT[id++] << ' ';
cout << BT[id] << endl;
}
}
return 0;
}
B 树的高度
- 求树的高度,BFS 的常规题。
- 参考代码如下。
#include<iostream>
#include<vector>
#include<queue>
const int maxn = 1010;
using namespace std;
int depth = 0;
struct node {
int layer;
vector <int> child;
}tree[maxn];
void bfs() {
queue <int> q;
q.push(1);
tree[1].layer = 1;
while (q.size()) {
int parent = q.front();
if (tree[parent].layer > depth)
depth = tree[parent].layer;
q.pop();
for (int i = 0; i < tree[parent].child.size(); i++) {
int child = tree[parent].child[i];
tree[child].layer = tree[parent].layer + 1;
q.push(child);
}
}
}
int main() {
int n, a, b;
cin >> n;
while (cin >> a >> b)
tree[a].child.push_back(b);
bfs();
cout << depth << endl;
return 0;
}