原文链接:http://kakazai.cn/index.php/Kaka/Pat/query/id/154
题目
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805407749357568
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
题意分析
- 题意
二叉排序树的递归定义:1)左子树的所有结点的值都小于根结点的值;2)右子树的所有结点的值都大于或等于根结点的值;3)左右子树也是一棵二叉排序树
完全二叉树的定义:满二叉树在最底层的最右边去掉一部分叶子结点就成了完全二叉树
给定一个序列,序列中元素都是不重复的,非负的。用这个序列来构造一棵树,既要是二叉排序树叶也要是完全二叉树。并且输出它的层次遍历。
范围:元素的值的范围[0,2000],元素的个数范围[1,1000]
- 分析
二叉排序树的特点是中序遍历是升序的,因此将序列升序排列就可以得到该树的中序遍历。
完全二叉树的特点是,将它的层次遍历存储在一维数组中,父结点的数组下标若是i,则左孩子的下标是2i+1,右子结点的下标是2i+2。
结合这两个特点,根据父结点取孩子节点,对该树进行中序遍历,得出的序列结果必然是升序的。
知识点与坑点
- 知识点
1)二叉排序树的中序遍历,完全二叉树的层次遍历
- 坑点
1)
拟合法
算法思路
1 对输入序列进行升序,得到中序遍历的结果
2 假设树的层次遍历存在一维数组cbt[]中,根据父结点与孩子结点的下标关系,对树进行中序遍历
3 中序遍历时,将第一步的中序结果镶嵌进去
4 遍历cbt[]数组,即得到层次遍历结果
代码-c++版
#include <cstdio>
#include <algorithm>
using namespace std;
/*数值范围*/
const int maxn = 1001; //最多有1000个结点
/*所有变量*/
int in[maxn]; //中序遍历
int level[maxn]; //层次遍历
int n; //结点数目
/* 中序遍历 */
int c = 0;
void inorder(int root) {
if (root >= n)return;
inorder(root*2+1);
level[root] = in[c]; //拟合中序遍历结果和过程
c++;
inorder(root * 2 + 2);
}
int main(){
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
sort(in+0, in + n); //对数组下标为[0,n)排序
inorder(0); //中序遍历
/* 按要求输出层次遍历 */
for (int i = 0; i < n; i++){
if(i!=0)printf(" ");
printf("%d",level[i]);
}
return 0;
}
代码-python版