This source file includes following definitions.
- CreateBTreeNode
- AddBTreeNode
- FindBTreeNode
- DeleteBTreeNode
- TreeSize
- BalanceBTree
#include "btree.h"
#include "memory.h"
extern long Ticks;
struct BTreeNode * CreateBTreeNode(int key, void * data)
{
struct BTreeNode * node = (struct BTreeNode *)AllocUMem(sizeof(struct BTreeNode));
node->key = key;
node->data = data;
node->lesser = 0;
node->greater = 0;
node->isDirty = 0;
node->timestamp = Ticks;
return node;
}
void AddBTreeNode(struct BTreeNode * btree, int key, void *data)
{
if (key > btree->key)
{
if (btree->greater)
AddBTreeNode(btree->greater, key, data);
else
btree->greater = CreateBTreeNode(key, data);
}
else
{
if (btree->lesser)
AddBTreeNode(btree->lesser, key, data);
else
(btree->lesser = CreateBTreeNode(key, data));
}
}
struct BTreeNode * FindBTreeNode(struct BTreeNode * btree, int key)
{
if (btree)
{
if (btree->key == key)
return btree;
else if (key > btree->key)
return FindBTreeNode(btree->greater, key);
else
return FindBTreeNode(btree->lesser, key);
}
else
return 0;
}
struct BTreeNode * DeleteBTreeNode(struct BTreeNode * btree, int key)
{
return btree;
}
int TreeSize(struct BTreeNode * btree)
{
int size = 1;
if (!btree)
return 0;
size += TreeSize(btree->lesser);
size += TreeSize(btree->greater);
return size;
}
struct BTreeNode * BalanceBTree(struct BTreeNode * btree)
{
int difference;
int nLesser = TreeSize(btree->lesser);
int nGreater = TreeSize(btree->greater);
difference = nLesser - nGreater;
if (difference < 0)
difference = -difference;
while (difference > 1)
{
struct BTreeNode *tempNode, *temp1Node, *temp2Node;
if (nLesser < nGreater)
{
tempNode = btree->greater;
if (!tempNode->lesser)
{
tempNode->lesser = btree;
}
else
{
while (tempNode->lesser)
{
temp2Node = tempNode;
tempNode = tempNode->lesser;
}
temp2Node->lesser = 0;
tempNode->lesser = btree;
temp2Node = tempNode;
while (temp2Node->greater)
temp2Node = temp2Node->greater;
temp2Node->greater = btree->greater;
}
btree->greater = 0;
btree = tempNode;
}
else
{
tempNode = btree->lesser;
if (!tempNode->greater)
{
tempNode->greater = btree;
}
else
{
while (tempNode->greater)
{
temp2Node = tempNode;
tempNode = tempNode->greater;
}
temp2Node->greater = 0;
tempNode->greater = btree;
temp2Node = tempNode;
while (temp2Node->lesser)
temp2Node = temp2Node->lesser;
temp2Node->lesser = btree->lesser;
}
btree->lesser = 0;
btree = tempNode;
}
difference -= 2;
}
if (btree->lesser)
btree->lesser = BalanceBTree(btree->lesser);
if (btree->greater)
btree->greater = BalanceBTree(btree->greater);
return btree;
}