直接中序往里面填就好了。。。。
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#define MAX 110
#define null -1
using namespace std;
int n;
struct Node {
int data;
int left;
int right;
};
Node t[MAX];
vector <int> a;
int pos = 0;
vector <int> ans;
void InOrder(int root) {
if (root != null) {
InOrder(t[root].left);
t[root].data = a[pos++];
InOrder(t[root].right);
}
}
void LevelOrder(int root) {
if (root != null) {
queue <int> q;
q.push(root);
while (!q.empty()) {
int top = q.front();
q.pop();
ans.push_back(t[top].data);
if (t[top].left != null) {
q.push(t[top].left);
}
if (t[top].right != null) {
q.push(t[top].right);
}
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
t[i].data = i;
cin >> t[i].left >> t[i].right;
}
a.resize(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
InOrder(0);
LevelOrder(0);
cout << ans[0];
for (int i = 1; i < n; i++) {
cout << " " << ans[i];
}
return 0;
}
本文介绍了一种通过中序遍历来填充二叉树节点数据的方法,并实现了基于此方法的层序遍历输出。具体步骤包括:首先定义二叉树结构;然后通过输入的先序遍历形式构建二叉树;接着使用已排序的数组按中序遍历的方式填充每个节点的数据;最后通过层序遍历打印填充后的二叉树节点数据。
1631

被折叠的 条评论
为什么被折叠?



