一、题目描述
Input Specification:
Output Specification:
For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.
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
二、解题思路
BST的简单题,我们把每个结点设置为一个结构体,包括里面的数据,左孩子和右孩子。值得注意的是,BST的中序遍历事实上就是所有数据从小到大排序的序列,基于这个事实,我们可以用中序遍历,把所有结点的数据补充完整。之后进行层序遍历即可。
三、AC代码
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 110;
int all[maxn];
int n, t = 0;
struct Node
{
int key, lchild, rchild;
}node[maxn];
void inOrder(int root) //中序遍历
{
if(root == -1) return;
inOrder(node[root].lchild);
node[root].key = all[t++];
inOrder(node[root].rchild);
}
void BFS(int root) //层序遍历
{
queue<int> q;
q.push(root);
int cnt = 0;
while(!q.empty())
{
int now = q.front();
q.pop();
cnt++;
printf("%d", node[now].key);
cnt == n ? printf("\n") : printf(" ");
if(node[now].lchild != -1) q.push(node[now].lchild);
if(node[now].rchild != -1) q.push(node[now].rchild);
}
return;
}
int main()
{
scanf("%d", &n);
for(int i=0; i<n; i++)
scanf("%d%d", &node[i].lchild, &node[i].rchild);
for(int i=0; i<n; i++)
scanf("%d", &all[i]);
sort(all, all+n);
inOrder(0);
BFS(0);
return 0;
}