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
递归创建CBST,通过底层结点数是否过半,判断左子树或者右子树为满。
层序遍历访问结点。/*2015.7.12*/ #include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; struct TNode{ int val; TNode* left; TNode* right; TNode(int x):val(x),left(nullptr),right(nullptr){} }; //递归创建CBST TNode* cbst(vector<int> &a,int begin,int end){ if(begin>end) return nullptr; int n=end-begin+1; TNode* root; if(n==1){ root=new TNode(a[begin]); return root; } int sum=0;//已用结点数 int level=1;//底层的坑数 while(sum+level<=n){//底层填满仍小于等于n sum+=level; level*=2; } int r=n-sum; if(r>level/2){//剩余的结点数超过底层一半,说明左子树满,且结点数与sum一样 root=new TNode(a[begin+sum]); root->left=cbst(a,begin,begin+sum-1); root->right=cbst(a,begin+sum+1,end); }else{//剩余结点数没过半,说明右子树满,且比sum少一层 sum=sum-level/2; root=new TNode(a[end-sum]); root->left=cbst(a,begin,end-sum-1); root->right=cbst(a,end-sum+1,end); } return root; } //层序遍历 vector<vector<int> > levelOrder(TNode* root){ vector<vector<int> > result; if(root==nullptr) return result; vector<int> level; queue<TNode*> cur,next; cur.push(root); while(!cur.empty()){ while(!cur.empty()){ TNode* tmp=cur.front(); cur.pop(); level.push_back(tmp->val); if(tmp->left!=nullptr) next.push(tmp->left); if(tmp->right!=nullptr) next.push(tmp->right); } result.push_back(level); level.clear(); swap(cur,next); } return result; } int main(){ int N; cin>>N; vector<int> a(N); for(int i=0;i<N;i++) cin>>a[i]; sort(a.begin(),a.end()); TNode* root=cbst(a,0,N-1); vector<vector<int> > result=levelOrder(root); cout<<root->val; for(auto it=result.begin()+1;it!=result.end();++it) for(auto itt=(*it).begin();itt!=(*it).end();++itt) cout<<" "<<*itt; return 0; }