题目
思路
题目描述:题目给定一个BST的结构,再给出一个输入序列来构造BST,(这样的二叉树是唯一的);
要求输出BST的层序遍历;
思路:给出的序列是无序的,可以先将其排序(增序);
二叉搜索树的中序遍历序列即排序后的输入序列;
可以利用中序遍历先建立序列中数据到对应节点的映射(数组实现);
这样树的结构和节点对应的数据都确定了,最后输出层序序列;
CODE ⇩⇩⇩
#include <bits/stdc++.h>
using namespace std;
int lt[100],rt[100],lis[100],mp[100];
queue<int> que;
static int cnt = 0;
void inOrder(int node){
if(node == -1) return;
inOrder(lt[node]);
mp[node] = lis[cnt++];
inOrder(rt[node]);
}
void levelOrder(int root){
que.push(root);
while(!que.empty()){
int it = que.front();
cout<<(it == root ? "" : " ")<<mp[it];
if(lt[it] != -1) que.push(lt[it]);
if(rt[it] != -1) que.push(rt[it]);
que.pop();
}
}
int main() {
int n; cin>>n;
for(int i = 0;i < n;i++) cin>>lt[i]>>rt[i];
for(int i = 0;i < n;i++) cin>>lis[i];
sort(lis,lis+n);
inOrder(0);
levelOrder(0);
return 0;
}