#include <stdio.h>
#include <stdlib.h>
#include "Collection.h"
void * Binary_Tree::Tree_Insert(void *pInfo, int (* cmp)(void *first, void *second))
{
int iCheck = 0;
roots *newroot = new roots;
roots *Z1 = root, *Z2 = NULL;
if(newroot != NULL)
{
newroot->pInfo = pInfo;
if(root == NULL)
{
root = newroot;
}
else
{
while(Z1)
{
if(cmp(Z1->pInfo, pInfo) >= 0)
{
Z2 = Z1;
Z1 = Z1->left;
}
else
{
Z2 = Z1;
Z1 = Z1->right;
}
}
if(cmp(Z2->pInfo, pInfo) >= 0)
{
Z2->left = newroot;
}
else
{
Z2->right = newroot;
}
}
newroot->flag = 1;
}
else
{
printf("Not added!");
}
return root;
}
void Binary_Tree::Tree_Walk(void *root, ORDER o, void (*action)(void *p))
{
switch(o)
{
case preorder: if(root != NULL)
{
if((int)((roots *)root)->flag != 0)
{
action(((roots *)root)->pInfo);
}
Tree_Walk(((roots *)root)->left, o, action);
Tree_Walk(((roots *)root)->right, o, action);
}
break;
case inorder: if(root != NULL)
{
Tree_Walk(((roots *)root)->left, o, action);
if((int)((roots *)root)->flag != 0)
{
action(((roots *)root)->pInfo);
}
Tree_Walk(((roots *)root)->right, o, action);
}
break;
case postorder: if(root != NULL)
{
Tree_Walk(((roots *)root)->left, o, action);
Tree_Walk(((roots *)root)->right, o, action);
if((int)((roots *)root)->flag != 0)
{
action(((roots *)root)->pInfo);
}
}
break;
default: printf("\nNo valid choice!");
}
}
void * Binary_Tree::GetRoot()
{
return root;
}
void Binary_Tree::Del(void *root)
{
if(root != NULL)
{
Del(((roots *)root)->left);
Del(((roots *)root)->right);
//delete infos
if(((roots *)root)->flag != 0)
{
free(((roots *)root)->pInfo);
}
delete root;
}
}
void *Binary_Tree::Delete(void *root, void *key, int(* cmp)(void *first, void *second), void (*del)(void *del_el))
{
int iCheck = 0;
void *help = NULL;
if(root != NULL)
{
help = ((roots *)root)->pInfo;
iCheck = cmp(((roots *)root)->pInfo, key);
if(iCheck != 0)
{
if(iCheck < 0)
{
help = Delete(((roots *)root)->right, key, cmp, del);
}
else
{
help = Delete(((roots *)root)->left, key, cmp, del);
}
}
else
{
if(help != NULL)
{
del(help);
((roots *)root)->flag = 0;
}
}
}
return help;
}