题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805407749357568
题目
1064 Complete Binary Search Tree (30分)
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 Specificationx:
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
解题思路
题意:给定一个数列,要求输出该序列数构成的完全二叉搜索树。
完全二叉搜索树(完全数与二叉排序数综合,CBST):在满足完全二叉树的基础上,非叶节点n的左子树元素均小于n的元素值,而右子树大于n的元素值。而完全二叉树的层序遍历具有的性质为,第i个元素输出下标为i(i从1计数)。
性质:对于下标x,2*x与2*x+1为x的左右孩子节点下标(注意下标 1<= index <=n)
思路:1、对于完全二叉搜索树,该树的中序遍历结果即为这些元素的非递减数列(及该数列的排序结果)。
2、现在题目要求,给定数列,来求该树的层序遍历,我们可以采用逆推的方式,以前我们是已知CBST来进行中序遍历,那么我们是否可以考虑任然采用中序遍历,只是对于CBST re[x]来说,我们虽然未知,但是我们知道该点元素值为num[ct],由此我们使用逆推法,根据中序遍历结果以及CSBT的性质,来得到我们re[x]中的原有元素值。
3、我们将给定的数列进行排序,得到排序结果数组(CBST):num
4、此时num[1]输出的数,即为CBST中序遍历的第一个数,依次类推得到所有的结果。
算法建模:
ct:该元素输出顺序
num:元素数列非递减排序
re:CBST,re[i] 第i个元素
x:下标
中序遍历 dfs:(x<=n)
dfs(2*x) //先左子树
re[x] = ct++;//num 中的x 输出的顺序为ct
dfs(2*x+1) //遍历右子树
解题代码
#include <bits/stdc++.h>
using namespace std;
//完全搜索二叉树
//
const int maxsize = 1010;
int re[maxsize];
int num[maxsize];
int n;
int ct = 1;
void dfs(int x){
if(x>n) return ;
dfs(2*x);
/*
中序遍历:printf("%d",num[x])
Xi元素输出的顺序:ct
*/
re[x] = ct++;//第一个输出的元素序号
dfs(2*x+1);
}
void init(){
cin>>n;
for(int i = 1 ;i <=n;i++){
cin>>num[i];
}
sort(num+1,num+n+1);
int sum = n;
dfs(1);
for(int i = 1 ; i <=n;i++){
cout<<num[re[i]];
if(i!=n) cout<<" ";
}
}
int main()
{
init();
return 0;
}