The binary sort tree has one property:
- The sequence obtained by the middle-order traversal is an ordered sequence
So sort the sequence given by the title, and then traverse a complete binary sorted tree with all node values empty (the complete binary tree has not been established, but the array does exist, so every node is Exist), assign the value of each node in the middle-order traversal according to the order of the sorted sequence, so that a complete binary tree is built!
The sequential traversal of the complete binary tree array is the in-order traversal of the complete binary tree.
# include <bits/stdc++.h>
using namespace std;
/* 二叉排序树有一个性质:中序遍历得到的序列是有序序列
所以将题目给定的序列排好序,然后将一个所有结点值为空的完全二叉排序树进行中序遍历,
把遍历中每一个结点的值按照排序好的有序序列的顺序赋值,这样一颗完全二叉树就建立好了!
对完全二叉树数组进行顺序遍历就是对完全二叉树进行中序遍历
*/
int A[1010];
int CBT[1010];
int N;
int idx = 0;
void inOrder(int root){
// 中序遍历给结点赋值
if(root > N) return;
inOrder(root*2); // 左子树
CBT[root] = A[idx++]; // 给结点赋值
inOrder(root*2 + 1); // 右子树
}
int main(){
cin >> N;
for(int i =0;i < N;++i)
scanf("%d", &A[i]);
sort(A, A+N);
inOrder(1);
for(int i = 1;i <= N;++i)
cout << CBT[i] << (i == N?"\n":" ");
return 0;
}