Hey guys,
I'm quite new to C programming and I'm having trouble implementing a binary tree. The program is to ask the user to enter "1" as an input, and when 1 is entered a student (enrolled in no units and displayed in ascending numerical order of ID number) is added. After the student is added into the binary tree the current height of the tree is given.
I understand simple binary tree's, however in this case having two structs really confuses me. One struct contains the relevant student information but the other structs data_item is a pointer to the student struct? The below code are the two structs used in the .h header file as well as the insert definition.
Code:
typedef struct student *student_ptr;struct student
{
int ID;
char *name;
int n_units;
char *units[1000];
};
typedef struct node *node_ptr;
struct node
{
student_ptr data_item;
node_ptr left;
node_ptr right;
};
node_ptr insert(int n, node_ptr tree);
The rest of the code below is contained in the .c file. I'm trying to write the insert function, however as the struct node's data_item is a pointer to the struct student I get confused. I understand I need to change to 'int n' parameter as well?
Code:
node_ptr insert(int n, node_ptr tree)
{
if(!tree)
{
tree = (node_ptr) malloc(sizeof(struct node));
tree->data_item = n;
tree->left = tree->right = NULL;
}
else if(n < tree->data_item)
{
tree->left = insert(n, tree->left);
}
else if(n > tree->data_item)
{
tree->right = insert(n, tree->right);
}
return tree;
}
If someone could point me in the right direction that would be greatly appreciated!
Thanks