I am a newbie in learning c..... So I am trying to create a tree structure from inputs like:
(2, 50) (4, 30) (9, 30) (10, 400) (-5, -40)
(7, 20) (19, 200) (20, 50) (-18, -200) (-2, 29)
(2, 67) (4, 35) (9, 45) (-18, 100)
Firstly, I have defined some data structures and auxiliary function as below:
typedef struct AVLTreeNode
{
int key; //key of this item
int value; //value (int) of this item
int height; //height of the subtree rooted at this node
struct AVLTreeNode *parent; //pointer to parent
struct AVLTreeNode *left; //pointer to left child
struct AVLTreeNode *right; //pointer to right child
} AVLTreeNode;
//data type for AVL trees
typedef struct AVLTree
{
int size; // count of items in avl tree
AVLTreeNode *root; // root
} AVLTree;
// create a new AVLTreeNode
AVLTreeNode *newAVLTreeNode(int k, int v)
{
AVLTreeNode *newNode;
newNode = malloc(sizeof(AVLTreeNode));
assert(newNode != NULL);
newNode->key = k;
newNode->value = v;
newNode->height = 0; // height of this new node is set to 0
newNode->left = NULL; // this node has no child
newNode->right = NULL;
newNode->parent = NULL; // no parent
return newNode;
}
// create a new empty avl tree
AVLTree *newAVLTree()
{
AVLTree *T;
T = malloc(sizeof(AVLTree));
assert(T != NULL);
T->size = 0;
T->root = NULL;
return T;
}
Then I wrote a function to insert each pair of data into the tree:
int InsertNode(AVLTree *T, int k, int v)
{
AVLTreeNode *currentNode = T->root;
AVLTreeNode *parent;
//if the tree/subtree is empty
if (currentNode == NULL)
{
currentNode = newAVLTreeNode(k, v);
}
//keys are equal
else
{
while (currentNode != NULL)
{
parent = currentNode;
if (k == currentNode->key)
{
if (v == currentNode->value)
{
return 0;
}
else if (v < currentNode->value)
{
currentNode = currentNode->left;
}
else if (v > currentNode->value)
{
currentNode = currentNode->right;
}
}
else if (k < currentNode->key)
{
currentNode = currentNode->left;
}
else if (k > currentNode->key)
{
currentNode = currentNode->right;
}
}
currentNode = newAVLTreeNode(k, v);
currentNode->parent = parent;
}
T->size++;
return 1;
}
I was expecting the values k and v in the function arguments would pass onto T->root->key, and T->root->value respectively, but it doesn't work..... Could someone help me to correct the code and explain to me the reason why my code is wrong please?