# 1099 Build A Binary Search Tree (30分)

1. 先构造好树的结构，然后记录中序遍历下数组的下标。
2. 将给出的值排序，按照中序遍历的下标顺序将各值填入树的结点中。
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
struct node {
int val, left, right;
}table[100];
vector<int> inorder;
void inorderTraverse(int cur) {
if (cur == -1)
return;
inorderTraverse(table[cur].left);
inorder.push_back(cur);
inorderTraverse(table[cur].right);
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int left, right;
cin >> table[i].left >> table[i].right;
}
vector<int> values(n);
for (int i = 0; i < n; i++) {
cin >> values[i];
}
sort(values.begin(), values.end());
inorderTraverse(0);
int i = 0;
for (int index : inorder) {
table[index].val = values[i++];
}
queue<int> q;
vector<int> res;
q.push(0);
while (!q.empty()) {
int cur = q.front();
res.push_back(table[cur].val);
q.pop();
if (table[cur].left != -1) {
q.push(table[cur].left);
}
if (table[cur].right != -1) {
q.push(table[cur].right);
}
}
for (int i = 0; i < n; i++) {
if (i != 0)
cout << " ";
cout << res[i];
}
}


©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客