二叉查找树中序遍历是有顺序的,层序遍历使用队列
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
struct node{
int key,num;
int left,right;
}Node[100];
int k[100],num=0;
void in_order(int index){
if(index==-1)
return;
in_order(Node[index].left);
Node[index].key = k[num++];
in_order(Node[index].right);
}
void le_order(){
queue<node> q;
q.push(Node[0]);
while(q.empty()==false){
node N=q.front();
if(N.num !=0)
cout<<' ';
cout<<N.key;
q.pop();
if(N.left!=-1)
q.push(Node[N.left]);
if(N.right!=-1)
q.push(Node[N.right]);
}
}
int main(){
int n;
cin >> n;
for(int i=0;i<n;i++){
cin>>Node[i].left>>Node[i].right;
Node[i].num = i;
}
for(int i=0;i<n;i++){
cin>>k[i];
}
sort(k,k+n);
in_order(0);
le_order();
return 0;
}