04-树6 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 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
这道题就我所知道已经有两种解法了:
第一种: 比较繁琐,我自己也是这么思考的,但实现过程太繁琐以及自己对递归的掌握不好,在编程中放弃了,结果看了陈越老师的思路竟然和我一样,可能这个思考过程更一般吧,利用了搜索树的 任意节点的左边的节点都小于该节点,右边节点都大于该节点以及已知节点数可知完整的二叉搜索树的结构来确定节点的;
总的老说,思路简单,实现复杂;
#include<iostream>
#include<vector>#include<algorithm>
#include<math.h>
using namespace std;
vector<int> tree,vi;
int getleftlength(int n){
int H=log2(n+1);
int X=n-pow(2,H)+1;
X=X<pow(2,H-1)?X:pow(2,H-1);
return pow(2,H-1)-1+X;
}
//方法一的核心算法:
void solve(int aleft,int aright,int root){int n=aright-aleft+1;
if(n==0) return;
int L=getleftlength(n);
tree[root]=vi[aleft+L];
int leftroot=2*root+1;
int rightroot=leftroot+1;
solve(aleft,aleft+L-1,leftroot);
solve(aleft+L+1,aright,rightroot);
}
//
int main()
{
int N; cin>>N;int flag=1;
tree.resize(N);
for(int i=0;i<N;i++){
int j;cin>>j;
vi.push_back(j);
}
sort(vi.begin(),vi.end());
solve(0,vi.size()-1,0);
for(int j=0;j<N;j++)
if(flag++==1)
cout<<tree[j];
else
cout<<" "<<tree[j];
}
方法二:利用搜索 二叉树中序遍历结果是升序的性质完美的简化了问题;相当于已知完整二叉搜索树中序遍历结果以及 按完整二叉树标下标后下标的中序遍历结果,再
一一对应即可;
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> tree,vi;
int N,cnt=1,flag=1;
void buildtree(int i){
if(i>N) return;
buildtree(2*i);
tree[i]=vi[cnt++]; 该部分相当于对下标进行中序遍历,并一一对应;
buildtree(2*i+1);
}
int main(){
cin>>N;vi.resize(N+1); tree.resize(N+1);
for(int i=1;i<=N;i++){
int j; cin>>j;
vi[i]=j;
}
sort(vi.begin(),vi.end());
buildtree(1);
cout<<tree[1];
for(int i=2;i<=N;i++)
cout<<" "<<tree[i];
return 0;
}