1064. Complete Binary Search Tree (30)

来源:互联网 发布:域名授权码在哪里 编辑:程序博客网 时间:2024/06/09 19:38

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:
101 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4

按照给出的序列构建完全二叉搜索树,并且层序遍历输出。这里用递归构建树。主要问题是计算左子树和右子树各有多少个节点。设当前节点数为n,则除去底层节点,总共有h=log2(n)层,然后用n减去2的h次方就能得到底层节点数。底层如果满了节点数会是2的h次方,所以底层节点数如果超过2的h-1次方,则左子树是满的,左子树底层节点数就是2的h-1次方,如果不超过,则左子树的底层节点数就等于上面得到的底层节点数。这样就能算出左子树的节点数,因此根节点的值和右子树的节点数也能求得,然后递归调用函数就行了。最后对构建的树层序遍历即可。


代码:

#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <vector>#include <algorithm>#include <cmath>#include <queue>using namespace std;struct node{int val;node *left;node *right;};vector<int>a;node *build(int left,int right){if(left>right) return NULL;node *root=new node();if(left==right){root->val=a[left];return root;}int n=right-left+1;int h=log(n)/log(2);int bottom=n-pow(2,h)+1;int l=((bottom>pow(2,h-1))?pow(2,h-1):bottom)+pow(2,h)/2-1;root->val=a[left+l];root->left=build(left,left+l-1);root->right=build(left+l+1,right);return root;}void levelorder(node *root){queue<node*>q;q.push(root);bool flg=true;while(!q.empty()){node* tmp=q.front();q.pop();if(flg){cout<<tmp->val;flg=false;}else{cout<<" "<<tmp->val;}if(tmp->left) q.push(tmp->left);if(tmp->right) q.push(tmp->right);}}int main(){int n;cin>>n;a.resize(n);for(int i=0;i<n;i++){cin>>a[i];}sort(a.begin(),a.end());node *root=build(0,n-1);levelorder(root);}


0 0