题目描述
A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
- Both the left and right subtrees must also be binary search trees.
Given the structure of a binary tree and a sequence of distinct integer keys, there is only one way to fill these keys into the tree so that the resulting tree satisfies the definition of a BST. You are supposed to output the level order traversal sequence of that tree. The sample is illustrated by Figure 1 and 2.
翻译:一棵二叉查找树(BST)按照以下格式递归的定义:
1.左子树只包含关键字小于该节点关键字的节点。
2.右子树只包含关键字大于该节点关键字的节点。
3.左右字数都必须也是二叉查找树。
给定一个二叉树的结构和一个由整数构成且键值唯一的数列。只有一个办法来将这些节点插入二叉树中且得到的二叉树满足BST的定义。你需要输出该树的层次遍历数列。图一和图二表示样例中的树。
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100) which is the total number of nodes in the tree. The next N lines each contains the left and the right children of a node in the format left_index right_index, provided that the nodes are numbered from 0 to N−1, and 0 is always the root. If one child is missing, then −1 will represent the NULL child pointer. Finally N distinct integer keys are given in the last line.
翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一行给定一个正整数N(<=100),表示树中的总结点数。接下来N行每行按照left_index right_index,的格式给出左孩子的节点位置和右节点的节点位置,假设节点被编号为1到N-1,并且0总是根。如果一个孩子为空,则用-1来表示NULL。最后一行将给出N个唯一整数键值。
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
解题思路
先用树的中序遍历来确定每一点对应的键值,然后通过队列来输出树的层次遍历。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<queue>
#include<algorithm>
#define INF 99999999
#define bug puts("Hello\n")
using namespace std;
int BST[110][3];
int v[110];
queue<int>q;
int n,ccount=0;
int find(int root){
if(BST[root][0]==-1);
else find(BST[root][0]);
BST[root][2]=v[ccount++];
if(BST[root][1]==-1);
else find(BST[root][1]);
}
void ans(){
q.push(0);
int flag=0;
while(!q.empty()){
int tmp=q.front();q.pop();
if(BST[tmp][0]!=-1)q.push(BST[tmp][0]);
if(BST[tmp][1]!=-1)q.push(BST[tmp][1]);
if(!flag)printf("%d",BST[tmp][2]),flag=1;
else printf(" %d",BST[tmp][2]);
}
printf("\n");
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d",&BST[i][0],&BST[i][1]);
}
for(int i=0;i<n;i++)scanf("%d",&v[i]);
sort(v,v+n);
find(0);
ans();
return 0;
}