还是中序遍历建树,只不过这次利用二叉树静态写法,因为给出结点编号的关系。
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 101;
struct node
{
int data;
int left, right;
}Node[maxn];
int num = 0, in[maxn], n;
void inorder(int root)
{
if (root == -1) return;
inorder(Node[root].left);
Node[root].data = in[num++];
inorder(Node[root].right);
}
void bfs(int root)
{
queue<int>q;
q.push(root);
int num = 0;
while (!q.empty())
{
int temp = q.front();
q.pop();
cout << Node[temp].data;
num++;
if (num < n)
cout << " ";
if (Node[temp].left != -1) q.push(Node[temp].left);
if (Node[temp].right != -1) q.push(Node[temp].right);
}
}
int main()
{
cin >> n; int l, r;
for (int i = 0; i < n; i++)
{
cin >> l >> r;
Node[i].left = l;
Node[i].right = r;
}
for (int i = 0; i < n; i++)
{
cin >> in[i];
}
sort(in, in + n);
inorder(0);
bfs(0);
return 0;
}