How do I add more nodes to my binary tree if A (left) and B (right) are already full? I just need to create a tree that is balanced. But I can't figure out how to add more data to the tree. Any help would be greatly appreciated.
Thanks in advance for any tipps.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct node
{
char *titel;
struct node *A;
struct node *B;
};
void display(struct node *leaf)
{
if (leaf != NULL)
{
display(leaf->A);
printf("%s\n",leaf->titel);
display(leaf->B);
}
}
struct node *insert(char* titel, struct node **leaf)
{
if (*leaf == 0)
{
*leaf = (struct node*)malloc(sizeof(struct node));
(*leaf)->titel = malloc(strlen(titel)+1);
strcpy((*leaf)->titel,titel);
(*leaf)->A = NULL;
(*leaf)->B = NULL;
}
else if ((*leaf)->A == NULL)
{
(*leaf)->A = insert(titel,&(*leaf)->A);
}
else if ((*leaf)->B == NULL )
{
(*leaf)->B = insert(titel,&(*leaf)->B);
}
//WHAT TO ADD HERE TO CREATE ANOTHER NODE?
return(*leaf);
}
int main(int argc, char const *argv[])
{
struct node *root = NULL;
insert("root",&root);
insert("chapter_1A",&root);
insert("chapter_1B",&root);
insert("chapter_2A",&root);
insert("chapter_2B",&root);
insert("chapter_3A",&root);
display(root);
return 0;
}
Output should be like a balanced binary tree. Mustn't be printed but stored like that in memory.
Actual output:
chapter_1A
root
chapter_1B
root
/ \
chapter_1A chapter_1B
/ \ / \
ch_2A ch_2B ch_3A ch_3B
and so on.