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 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 0Sample Output:
6 3 8 1 5 7 9 0 2 4
题意:
给定n个数,先建立完全排序二叉树(即节点的左孩子中的所有节点均小于该节点,节点的右孩子中的所有节点均大于该节点),再按照广度优先遍历的方式输出每个节点。
刚开始写这道题的时候,希望模拟出来这道题,发现非常麻烦,首先要排序,再建立一棵完全排序二叉树,再用广搜依次输出每个节点。后来代码敲着敲着,发现,这样好像会超时,而且貌似有非常简便的方法。
事实上、我们可以通过中序遍历直接求解这道题。因为完全排序二叉树的排序方法,它的结果输出就是通过中序排序实现的(满足左孩子<父节点<右孩子),故中序遍历的序列即为排好序的序列。
因此,我们只需要将原来已经排好序的序列按照中序遍历存储,即为答案,同样,输出的结果再按照中序遍历的方式输出,即为排好序的序列。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int n,a[1005],b[1005],index,num=0;
void dfs(int odex)
{
if(odex>=n)
{
num++;
return;
}
dfs(2*odex+1);
b[odex]=a[num-1];
dfs(2*odex+2);
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
dfs(0);
for(int i=0;i<n-1;i++)
printf("%d ",b[i]);
printf("%d\n",b[n-1]);
}
return 0;
}
结果: