A1099
Description:
有关二叉查找树BST的描述见题目 A1043 Is It a Binary Search Tree
现给出一个二叉树结构以及一组互不相同的数据,仅存在一种将这些数据填入这颗二叉树的方法使其成为一颗BST,求这颗BST的层次遍历序列。
算法构思:
- BST具有中序遍历序列元素值递增的特性
- 所给数据序列升序排序后,即得到BST的中序遍历序列
- 中序遍历二叉树,依次将遍历到的节点填入数据,二叉树构建完成
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 105;
struct node{
int key;
int left;
int right;
}Node[maxn];
int keys[maxn], ans[maxn]; //存放数据序列及答案
int n, indexx = 0;
void inOrder(int root){ //中序遍历
if(Node[root].left != -1) inOrder(Node[root].left);
Node[root].key = keys[indexx++];
if(Node[root].right != -1) inOrder(Node[root].right);
}
void BFS(){ //广搜层次遍历
queue<int>q;
q.push(0);
while(!q.empty()){
ans[indexx++] = Node[q.front()].key;
if(Node[q.front()].left != -1) q.push(Node[q.front()].left);
if(Node[q.front()].right != -1) q.push(Node[q.front()].right);
q.pop();
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
memset(Node, -1, sizeof(Node));
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d%d", &Node[i].left, &Node[i].right);
}
for(int i = 0; i < n; i++){
scanf("%d", &keys[i]);
}
sort(keys, keys+n);
inOrder(0);
indexx = 0;
BFS();
for(int i = 0; i < n; i++){
if(i != 0)
printf(" ");
printf("%d", ans[i]);
}
return 0;
}