题目
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.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
Sample Input:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
解题思路
二叉搜索树的中序序列一定是非递减的,由于本题没有重复的数字,因此,该中序序列是严格递增的,即将读入的数字进行升序排列后便可得到二叉树的中序遍历的结果。
又因为本题的二叉树是完全二叉树,因此它可以用数组来存储,且结点a[i]
若有左右孩子孩子结点,则左右孩子结点在层序遍历的数组当中的对应元素是a[2*i]、a[2*i+1]
(数组元素下标从1开始)。因此,要将中序遍历结果转化为层序遍历的结果,需要利用递归的方法:不断找到层序遍历的数组中对应于中序序列元素的下标,并将中序序列元素存入层序遍历数组,最后在按照数组下标顺序输出。
难点
中序序列转层遍历序列的递归函数。首先,需要明确,递归是利用“结点a[i]
若有左右孩子孩子结点,则左右孩子结点在层序遍历的数组当中的对应元素是a[2*i]、a[2*i+1]
(数组元素下标从1开始)”这一规律,将中序序列的“左根右”对应到层遍历序列的数组中去,在中序序列中连续存储的数字,在层遍历序列中的下标是跳着的,而这个“跳着”就可以用递归来获得。具体体现在:
- 先递归找到层遍历序列最后一层最左侧的结点的下标,对应于中序序列的第一个元素;
- 再向上回溯找到其父亲结点下标;
- 再寻找父亲的右孩子下标;
- 如此循环,直到中序序列所有元素都被遍历到并存入了层序遍历序列。
总体而言,这种中序转层序的方法,是在以中序序列的搜索方式“左根右”遍历二叉树,借助层序序列的下标规律和递归对应到层序序列数组中,最后输出。
代码
#include<bits/stdc++.h>
using namespace std;
int N,a[1001],k=1,q[1001];
void dfs(int s){
if ((s*2)<=N)
dfs(s*2);
q[s] = a[k++];
if (((s*2)+1)<=N)
dfs(s*2+1);
}
int main(){
int i;// N (≤1000)
scanf("%d",&N);
for (i=1;i<=N;i++)
scanf("%d",&a[i]);
sort(a+1,a+1+N);//获得了中序遍历的结果
dfs(1);
for(i=1;i<=N;i++)
{
if (i!=1)
printf(" ");
printf("%d",q[i]);
}
return 0;
}