二叉搜索树(BST)定义为具有以下属性的二叉树:
1.任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值
2.任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值
3.任意节点的左、右子树也分别为二叉查找树
完全二叉树(CBT)的深度为k,除第k层外,其他各层(1~(k-1)层)的节点数都达到最
大值,且第k层所有的节点都连续集中在最左边。
现在,给定一个键值互不相同的非负整数序列,构造一颗树既是CBT,也是BST。请你输出
这个BST的层次遍历序列。
【输入形式】
每个输入文件的第一行为一个正整数N(≤20),即二叉树中结点的总数。第二行给出了N
个不同的非负键值序列。
注意:每一行中的所有数字都用一个空格隔开,并且不大于50。
【输出形式】
相应完全搜索二叉树的层次遍历序列输出在一行中。一行中的所有数字必须由一个空格隔
开,并且行首和行尾不得有多余的空格。
举例:
给定10个结点,序列为1 2 3 4 5 6 7 8 9 0。根据完全二叉树和二叉搜索树的定义得到所
求二叉树层次遍历序列为 6 3 8 1 5 7 9 0 2 4。
#ifndef BINTREE_H
#define BINTREE_H
template<typename E>class BinTree
{
private:
int n;
int pos;
int index;
E *a;
E *b;
public:
BinTree(){}
virtual ~BinTree(){}
virtual void inOrder(int)=0;
virtual void levelOrder()=0;
};
#endif
#ifndef BBINTREE_H
#define BBINTREE_H
#include "BinTree.h"
#include <algorithm>
#include <iostream>
using namespace std;
template<typename E>class BBinTree:public BinTree<E>
{
private:
int n;
int pos;
int index;
E *a;
E *b;
public:
BBinTree(int x)
{
n=x;
pos=1;
a=new E[n+1];
b=new E[n+1];
for(int i=1;i<=n;i++)cin>>a[i];
sort(a+1,a+n+1);
}
void inOrder(int index)
{
if(index*2<=n)inOrder(index*2);
b[index]=a[pos++];//遍历赋值
if(index*2+1<=n)inOrder(index*2+1);
}
void levelOrder()
{
for(int i=1;i<=n;i++)
{
cout<<b[i];
if(i!=n)cout<<" ";
}
}
~BBinTree(){}
};
#endif
#include<iostream>
#include"BBinTree.h"
using namespace std;
int main()
{
int x;
cin>>x;
BBinTree<int>bt(x);
bt.inOrder(1);
bt.levelOrder();
return 0;
}