还是二叉树的各种基本功
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {};
TreeNode(int _val) : val(_val), left(nullptr), right(nullptr) {};
TreeNode(int _val, TreeNode* _left, TreeNode* _right) : val(_val), left(_left), right(_right) {};
~TreeNode() {};
};
int n, l, r;
TreeNode* buildTree(vector<pair<int, int>>& node_infos, int index) {
// recursion exit condition
if (index == -1) return nullptr;
auto root = new TreeNode(index);
root->left = buildTree(node_infos, node_infos[index].first);
root->right = buildTree(node_infos, node_infos[index].second);
return root;
}
void fill(TreeNode* root, vector<int>& vals, int& idx) {
if (!root) return;
fill(root->left, vals, idx);
root->val = vals[idx++];
fill(root->right, vals, idx);
}
void levelOrder(TreeNode* root) {
queue<TreeNode*> q{{root}};
while (not q.empty()) {
auto cur = q.front(); q.pop();
printf("%d ", cur->val);
if (cur->left) q.emplace(cur->left);
if (cur->right) q.emplace(cur->right);
}
}
int main(void) {
scanf("%d", &n);
vector<pair<int, int>> node_infos(n);
for (int i = 0; i < n; ++i) {
scanf("%d %d", &l, &r);
node_infos[i] = {l, r};
}
vector<int> vals(n);
for (int i = 0; i < n; ++i) cin >> vals[i];
sort(begin(vals), end(vals));
auto root = buildTree(node_infos, 0);
int idx = 0;
fill(root, vals, idx);
levelOrder(root);
}