Recently wrote a simple two-fork tree, only for reference, the code is as follows:
#include <iostream>
using namespace Std;
typedef char T;
Class BST
{
struct Node
{
T data;
node* L;
node* R;
Node (const t& D):d Ata (d), L (), R () {}
Node (const t& d,node* l,node* R):d ATA (d), L (L), R (r) {}
};
typedef node* Tree;
node* RP;
int n;
Public
BST (): RP (), n () {}
~bst ()
{
Clear ();
}
void Clear ()
{
Clear (RP);
n = 0;
}
void Insert (const t& D)
{
Insert (Rp,new Node (d));
++n;
}
tree& Find (const t& D)
{
return find (RP,D);
}
void Travel () const
{
Travel (RP);
cout << Endl;
}
BOOL Empty () const
{
return RP = = NULL;
}
int size () const
{
return n;
}
BOOL Remove (const t& D)//delete node of specified value in tree
{
tree& t = find (d);
if (t = = NULL) return false;
node* p = t;
if (t->l!= NULL) Insert (T->R,T->L);
t = t->r;
Delete p;
--n;
return true;
}
Const t& root () const
{
if (RP = null) throw "null";
Return rp->data;
}
void Update (const t& olddata,const t& NewData)//Modify node data
{
if (remove (olddata))
Insert (NewData);
}
Private
static void Insert (tree& t,node* p)//Insert a node in the tree
{
if (t = = NULL)
t = P;
else if (P->data < T->data)
Insert (T->L,P);
Else
Insert (T->R,P);
}
Static tree& Find (tree& t,const t& D)//returns the root pointer of a subtree that has D as the root node
{
if (t = = NULL) return t; Didn't find
else if (t->data = = d) return t; Got it
else if (D < t->data)
return find (T->L,D);
Else
return find (T->R,D);
}
static void travel (tree T)//traversal
{
if (t!= NULL)
{
Travel (T->L);
cout << t->data << ';
Travel (T->R);
}
}
static void Clear (tree& t)//Empty
{
if (t!= NULL)
{
Clear (T->l);
Clear (T->r);
Delete T;
t = NULL;
}
}
static int high (tree T)
{
if (t = = NULL) return 0;
int lh = high (t->l);
int RH = high (T->R);
Return 1+ (LH>RH?LH:RH);
}
};
int main ()
{
BST b;
B.insert (' K ');
B.insert (' s ');
B.insert (' f ');
B.insert (' t ');
B.insert (' a ');
B.insert (' m ');
B.insert (' x ');
B.insert (' e ');
B.travel ();
B.remove (' K ');
B.travel ();
B.update (' x ', ' * ');
B.travel ();
while (!b.empty ())
B.remove (B.root ());
cout << "Size:" << b.size () << Endl;
B.travel ();
return 0;
}