目录
1,题目描述
Sample Input:
9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42
Sample Output:
58 25 82 11 38 67 45 73 42
题目大意
给定一棵二叉搜素树的结构和序列,要求按照此结构,将元素填充进去,并且输出层次遍历序;
2,思路
利用BST的特点:中序遍历即元素的增序排列;
数据结构
- struct node{
int left, right;
}tree[102]表示树,tree的下标即节点的编号,元素对应左右子树的编号; - int data[102]:存放原始数据(需要排序);
- int BST[102]:BST上的节点对应的元素。下标代表节点编号,元素代表节点对应的值;
- vector<int> ans:将层次遍历的结果存入ans中;
算法
- 将树的结构存入tree中:
- 接受元素,并排序:
- 利用BST的特点,中序遍历BST,并填充BST数组:
- 将层次遍历序填入ans中:
3,AC代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int left, right;
}tree[102];
int data[102], BST[102], N, pos;//data存放原始序列 BST下表代表节点编号,元素代表节点对应的值 pos指向data中数据位置
vector<int> ans;
void inOrder(int root){ //利用BST中序遍历的特点 将元素与BST上的节点对应
if(root == -1) return;
inOrder(tree[root].left);
BST[root] = data[pos++]; //节点与值相对应
inOrder(tree[root].right);
}
void bfs(int root){ //层次遍历
queue<int> q;
q.push(root);
while(!q.empty()){
int n = q.front();
ans.push_back(BST[n]);
q.pop();
if(tree[n].left != -1) q.push(tree[n].left);
if(tree[n].right != -1) q.push(tree[n].right);
}
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d", &N);
for(int i = 0; i < N; i++)
scanf("%d %d", &tree[i].left, &tree[i].right);
for(int i = 0; i < N; i++)
scanf("%d", &data[i]);
sort(data, data + N); //BST的中序遍历 即元素的增序排序
pos = 0;
inOrder(0);
bfs(0);
printf("%d", ans[0]);
for(int i = 1; i < N; i++)
printf(" %d", ans[i]);
return 0;
}
4,解题过程
一发入魂