#include"tree.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
static SeekItem( const Item * pi, Tree * ptree);
static Node * MakeNode(const Item * pi);
static bool ToLeft(const Item *pi1, const Item * pi2);
static bool ToRight(const Item *pi1, const Item * pi2);
bool AddITem(const Item * pi, Tree * ptree)
{
Node * new_node;
if (TreeIsFull(ptree))
{
fprintf(stderr, "Tree is full.\n");
return false;
}
if (SeekItem(pi, ptree).child != NULL)
{
fprintf(stderr, "Attemppted to add duplicate item\n");
return false;
}
new_node = MakeNode(pi);
if (new_node == NULL)
{
fprintf(stderr, "Couldn't create node\n");
return false;
}
ptree->size++;
if (ptree->root == NULL)
ptree->root = new_node;
else
AddNode(new_node, ptree->root);
return true;
}
static Node * MakeNode(const Item * pi)
{
Node * new_node;
new_node = (Node *)malloc(sizeof(Node));
if (new_node != NULL)
{
new_node->item = *pi;
new_node->left = new_node->right = NULL;
return new_node;
}
else
return NULL;
}
static void AddNode(Node * new_node, Node * root)
{
if (ToLeft(&new_node->item, &root->item))
{
if (root->left == NULL)
root->left = new_node;
else
AddNode(new_node, root);
}
else if (ToRight(&new_node->item, &root->item))
{
if (root->right == NULL)
root->right = new_node;
else
AddNode(new_node, root);
}
else
{
fprintf(stderr, "location error in AddNode()\n");
exit(1);
}
}
static bool ToLeft(const Item *pi1, const Item * pi2)
{
int comp1;
if ((comp1 = strcmp(pi1->petname, pi2->petname)) < 0)
return true;
else if (comp1 = 0 && strcmp(pi1->petkind, pi2->petkind) < 0)
return true;
else
return false;
}
static bool toRight(const Item * pi1, const Item * pi2)
{
int comp1;
if ((comp1 = strcmp(pi1->petname, pi2->petname)) > 0)
return true;
else if (comp1 = 0 && strcmp(pi1->petkind, pi2->petkind) > 0)
return true;
else
return false;
}