建立二叉搜索树,id指的是在中序遍历过程中,对应节点的索引
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
/**
* 建立二叉搜索树
* @return
*/
struct TreeNode{
int id;
int val;
TreeNode* left;
TreeNode* right;
};
using namespace std;
int id;
void preOrder(TreeNode* node){
if(node== nullptr){
return;
}
preOrder(node->left);
node->id=id;
id++;
preOrder(node->right);
}
void levelOrder(TreeNode* root,vector<int>& vector1){
queue<TreeNode*> queue1;
queue1.push(root);
while (!queue1.empty()){
auto node=queue1.front();
queue1.pop();
vector1.push_back(node->val);
if(node->left!=nullptr){
queue1.push(node->left);
}
if(node->right!=nullptr){
queue1.push(node->right);
}
}
}
int main() {
int N;
cin>>N;
TreeNode* nodes[N];
for (int i = 0; i < N; ++i) {
nodes[i]=new TreeNode();
}
for (int j = 0; j < N; ++j) {
int s1,s2;
cin>>s1>>s2;
if(s1!=-1){
nodes[j]->left=nodes[s1];
}
if(s2!=-1){
nodes[j]->right=nodes[s2];
}
}
int nums[N];
for (int i= 0; i < N; ++i) {
cin>>nums[i];
}
sort(nums,nums+N);
preOrder(nodes[0]);
for (int i = 0; i < N; ++i) {
nodes[i]->val=nums[nodes[i]->id];
}
vector<int> vector1;
levelOrder(nodes[0],vector1);
cout<<vector1[0];
for (int i = 1; i < N; ++i) {
cout<<" "<<vector1[i];
}
return 0;
}