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、递归函数Solve的递归基如果在GetLeftLength之后,则从vec1到vec2的赋值语句也需要在递归基之前。
#include <iostream> #include <vector> #include <cmath> using namespace std; int GetLeftLength(int n)//个数为n的完全二叉树的左子树的结点个数 { int h=log2(n+1); int N=n-(pow(2, h)-1); int add=0; add= N<pow(2, h-1)? N:pow(2, h-1); return (pow(2, h-1)-1+add); } void Solve(vector<int>& vec1,vector<int>& vec2,int left,int right,int root) { int n=right-left+1; int num=GetLeftLength(n); vec2[root]=vec1[left+num]; if (num==0) { return; } int mid_l=left+num-1;//当前结点的左子树在有序数列中的最后一个结点的位置 int mid_r=mid_l+2;//当前结点的右子树在有序数列中的第一个结点的位置 int l=2*root+1;//当前结点的左孩子在层次遍历时的序号(从0开始) int r=l+1;//当前结点的右孩子在层次遍历时的序号 Solve(vec1, vec2, left, mid_l, l);//递归处理当前结点的左子树 Solve(vec1, vec2, mid_r, right,r);//递归处理当前结点的右子树 } int main() { int N=0; int data; cin>>N; vector<int> vec1(N);//存放初始输入队列 vector<int> vec2(N);//按顺序存放层次遍历二叉树时的每个结点 for (int i=0; i<N; ++i) { cin>>data; vec1[i]=data; } sort(vec1.begin(), vec1.end()); Solve(vec1, vec2, 0, N-1, 0); int flag=0; for (int i=0; i<vec2.size(); ++i) { if (flag==0) { flag=1; cout<<vec2[i]; }else { cout<<' '<<vec2[i]; } } return 0; }