题目
思路
静态存储数组,然后使用中序遍历生成二叉搜索树,层序输出即可
代码
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
const int nmax =105;
typedef struct Node {
int key, lchild, rchild;
};
vector<Node> tree;
int key[nmax];
int _index = 0;
void DFS(int cur) {
if (tree[cur].lchild != -1)
DFS(tree[cur].lchild);
tree[cur].key = key[_index++];
if (tree[cur].rchild != -1)
DFS(tree[cur].rchild);
}
void LevelRound() {
queue<int> q;
cout<<tree[0].key;
if (tree[0].lchild != -1)
q.push(tree[0].lchild);
if (tree[0].rchild != -1)
q.push(tree[0].rchild);
while (!q.empty()) {
int tmp = q.front();
q.pop();
cout << " " << tree[tmp].key;
if (tree[tmp].lchild != -1)
q.push(tree[tmp].lchild);
if (tree[tmp].rchild != -1)
q.push(tree[tmp].rchild);
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int lchild, rchild;
cin >> lchild >> rchild;
Node node = { 0,lchild,rchild };
tree.emplace_back(node);
}
for (int i = 0; i < n; ++i)
cin >> key[i];
sort(key, key + n);
DFS(0);
LevelRound();
return 0;
}