indexedBinarySearchTree 索引二叉树总
#include<iostream>
#include<queue>// 队列
#include<stack>
using namespace std;
template<class T>
struct binaryTreeNode{
T element;
binaryTreeNode<T> *leftChild,*rightChild;//三个域
int leftSize;
//三个构造
binaryTreeNode(){leftChild=rightChild=NULL;leftSize=0;}
binaryTreeNode(const T& theElement){element=theElement;leftChild=rightChild=NULL;leftSize=0;}
binaryTreeNode(const T& theElement,binaryTreeNode<T > *left,binaryTreeNode<T > *right,int Lsize){
element=theElement;
leftChild=left;
rightChild=right;
leftSize=Lsize;
}
};
template<class K,class E>
class IndexedBSTree{
virtual ~IndexedBSTree(){}
virtual pair<K,E>* find(K k) =0;//假定为KEY为int类型
virtual pair<K,E>* get(int index)=0;//返回索引的数对 pair 其实就是按大小排序 从0开始
virtual void insert(pair<K,E>& p);// 插入数对
virtual void erase(K k)=0;// 删除数对
virtual void ascend()=0;// 按升序输出序列
};
template<class K,class E>
class indexedBinarySearchTree{
public:
~indexedBinarySearchTree();//1
indexedBinarySearchTree();//1
bool empty(){return Root==NULL;}//1
pair<K,E>* find(K k);//1
pair<K,E>* get(int index);//1
void insert(pair<K,E>& p);//1
void erase(K k);//1
void ascend();//升序 中叙便利
void show();//层序遍历
binaryTreeNode<pair<K,E> >* ReRoot(){return Root;}
//
void outputRange(K theLow,K theHigt);//14.8
void deleteMax();//删除最大元素
int treeHeight(){return treeHeight(Root);}
void sort(E *element,binaryTreeNode<pair<K,E> >* root);
private:
void inOredr(binaryTreeNode<pair<K,E> >*root);
void deleteTree(binaryTreeNode<pair<K,E> >*root);
int treeHeight(binaryTreeNode<pair<K,E> >* root);
void outputRange(binaryTreeNode<pair<K,E> >* root, K theLow,K theHigt);
binaryTreeNode<pair<K,E> > *Root;
int TreeSize;
};
template<class K,class E>
void
indexedBinarySearchTree<K,E>::outputRange(K theLow,K theHigt){
binaryTreeNode<pair<K,E> > * temp=Root;
while(temp->element.first>theHigt)
temp=temp->leftChild;//定位到higt子树
outputRange(temp,theLow,theHigt);
cout<<endl;
}
template<class K,class E>
void
indexedBinarySearchTree<K,E>::outputRange(binaryTreeNode<pair<K,E> >* root, K theLow,K theHigt){
if(root==NULL)
return ;
outputRange(root->leftChild,theLow,theHigt);
if(root->element.first>=theLow&&root->element.first<=theHigt)
cout<<root->element.second<<" ";
outputRange(root->rightChild,theLow,theHigt);
}
template<class K,class E>
void
indexedBinarySearchTree<K,E>::ascend(){
inOredr(Root);
cout<<endl;
}
template<class K,class E>
void
indexedBinarySearchTree<K,E>::inOredr(binaryTreeNode<pair<K,E> >*root){
if(root==NULL)
return ;
if(root->leftChild!=NULL) inOredr(root->leftChild);
cout<<root->element.second<<" ";
if(root->rightChild!=NULL) inOredr(root->rightChild);
}
template<class K,class E>
void
indexedBinarySearchTree<K,E>::show(){
queue<binaryTreeNode<pair<K,E> >* >q;
binaryTreeNode<pair<K,E> >* temp;
q.push(Root);
while(!q.empty()){
temp=q.front();
q.pop();
cout<<temp->element.second<<" ";
if(temp->leftChild!=NULL)
q.push(temp->leftChild);
if(temp->rightCh