I have a book structure that contains a book title, url, and student name. I want to insert this data into a binary tree. I have already coded these functions but am not able to get an output when trying to print the tree.
1) Does my insert function look correct?
2) Does my printTree function look correct?
3) When I call on the printTree function I am passing pointer. If I want to just print from the root down what do I pass as the root?
Relevant code is as follows:
typedef struct book {
char title[75];
char url[75];
char student[50];
} BOOK;
struct tree_node {
BOOK data;
struct tree_node *left;
struct tree_node *right;
};
int insert_book() { // insert an new book
BOOK contact;
cout << endl << "@Inserting Book.........." << endl;
cout << "Enter the Book Title: ";
cin.ignore();
cin.getline(contact.title, 75);
cout << "Enter the Book URL: ";
cin.getline(contact.url, 75);
cout << "Enter the Student: ";
cin.getline(contact.student, 50);
void insert(BOOK, tree_node);
return 0;
}
struct tree_node * insert(BOOK contact, struct tree_node* node) {
if(node == NULL)
return(create_node(contact));
else if(strcmp(contact.student, node->data.student) <= 0)
node->left = insert(contact, node->left);
else if(strcmp(contact.student, node->data.student) >= 0)
node->right = insert(contact, node->right);
return (node);
}
struct tree_node* create_node(BOOK contact) {
struct tree_node* node = new(struct tree_node);
node->data = contact;
node->left = NULL;
node->right = NULL;
return(node);
}
void printTree(struct tree_node* node) {
if (node == NULL)
cout << "Empty!" << endl;
if(node != NULL) {
printTree(node->left);
printf("%d ", node->data);
printTree(node->right);
}
}
Also a side note, you are using c++, but coding in a very c style manner. I’d consider reorganizing the code for readability.