1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include "Queue.cpp"
#include "Stack.cpp"
#include "BTree.h"
#include<iostream>
using namespace std;
template <class ItemType>
int BTree<ItemType>::R_Height(TreePtr t)
{
if (t==NULL)
return 0;
int LTHT=R_Height(t->Lt);
int RTHT=R_Height(t->Rt);
if (LTHT>=RTHT)
{
return(LTHT+1);
}
else
return(RTHT+1);
}
template <class ItemType>
int BTree<ItemType>::R_Count(TreePtr t)
{
if (t==NULL)
return 0;
int LTCT=R_Count(t->Lt);
int RTCT=R_Count(t->Rt);
return (RTCT+LTCT+1);
}
template<class ItemType>
void BTree<ItemType>::R_Insert(TreePtr &t,ItemType x, int lev,int bal)
{
bool GoLt;
if(t==NULL)
{
t= new NodeType<ItemType>(x,lev);
t->Lt=t->Rt=NULL;
}
else
{
GoLt=rand()%2;
if(GoLt)
R_Insert(t->Lt,x,lev+1,bal);
else
R_Insert(t->Rt,x,lev+1,bal);
}
}
template<class ItemType>
void BTree<ItemType>::R_PreOrder(TreePtr t,ostream& output)
{
if(t!=NULL)
{
output<<t->item<<"("<<t->level<<")";
R_PreOrder(t->Lt,output);
R_PreOrder(t->Rt,output);
}
}
template<class ItemType>
void BTree<ItemType>::R_InOrder(TreePtr t,ostream& output)
{
if(t!=NULL)
{
R_InOrder(t->Lt,output);
output<<t->item<<"("<<t->level<<")";
R_InOrder(t->Rt,output);
}
}
template<class ItemType>
void BTree<ItemType>::R_PostOrder(TreePtr t,ostream & output)
{
if(t!=NULL)
{
R_PostOrder(t->Lt,output);
R_PostOrder(t->Rt,output);
output<<t->item<<"("<<t->level<<")";
}
}
template<class ItemType>
void BTree<ItemType>::BFS(ostream &output)
{
TreePtr t=Tree;
Queue<TreePtr>q;
q.enqueue(t);
while(!q.IsEmpty())
{
q.dequeue(t);
output<<t->item<<"("<<t->level<<")";
if(t->Lt!=NULL) q.enqueue(t->Lt);
if(t->Rt!=NULL) q.enqueue(t->Rt);
}
}
template<class ItemType>
void BTree<ItemType>::DFS(ostream &output)
{
TreePtr t=Tree;
Stack<TreePtr>s;
s.push(t);
while(s.IsEmpty())
{
s.pop(t);
output<<t->item<<"("<<t->level<<")";
if(t->Rt!=NULL) s.push(t->Rt);
if(t->Lt!=NULL) s.push(t->Lt);
}
}
template<class ItemType>
void BTree<ItemType>::R_Clear(TreePtr &t)
{
if (t!=NULL)
{
R_Clear(t->Lt);
R_Clear(t->Rt);
delete t;
t=NULL;
}
}
BTree<int>BT;
|