题目来源:PAT (Advanced Level) Practice
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.
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.
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
words:
recursively 递归地 structure 结构 illustrated 说明,表明
题意:
给定n个结点的左右孩子信息和n个数,要求输出这n个数构成的二叉搜索树的层序遍历序列;
思路:
1. 根据n个结点的左右孩子信息创建二叉树,由于本题的左右孩子信息是数组下表,所有我们采用包含数据域和左右孩子下标的结构体数组来存储树;
2. 二叉搜索树的中序遍历序列是一个有序序列,所以将题目给定的n个数先升序排列,然后通过中序遍历依次填入到二叉树的结点中去;
3. 层序遍历创建的二叉搜索树,输出层序遍历序列;
//PAT ad 1099 Build A Binary Search Tree
#include <iostream>
using namespace std;
#include <algorithm>
#include <queue>
#define N 100
struct bt //二叉树
{
int data;
int left;
int right;
}p[N];
int a[N],k=0;
void inOrder(int r) //中序遍历
{
if(r!=-1)
{
inOrder(p[r].left);
p[r].data=a[k++];
inOrder(p[r].right);
}
}
string cen;
void cenOrder(int r) //层序遍历
{
queue<int> q;
q.push(r); //根结点
while(!q.empty())
{
int x=q.front();q.pop();
cen+=to_string(p[x].data)+" ";
if(p[x].left!=-1) //左结点入队
q.push(p[x].left);
if(p[x].right!=-1) //右结点入队
q.push(p[x].right);
}
}
int main()
{
int n,i;
cin>>n;
for(i=0;i<n;i++) //输入
cin>>p[i].left>>p[i].right;
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n); //排序
inOrder(0); //中序遍历
cenOrder(0); //层序遍历
cen.pop_back(); //舍掉末尾空格
cout<<cen<<endl;
return 0;
}