#include #include struct b_node { int key; struct b_node *left; struct b_node *right; }; struct b_node* init_node(int key) { struct b_node *node = malloc(sizeof(struct b_node)); if (!node) { printf("Error initializing the node\n"); goto out; } node->key = key; node->left = NULL; node->right = NULL; out: return node; } struct b_node* search_node(struct b_node *ROOT, int key) { } void alloc_root(struct b_node **ROOT) { int key; struct b_node *new; printf("Type the ROOT key: "); scanf(" %d", &key); new = malloc(sizeof(struct b_node)); new->key = key; new->left = NULL; new->right = NULL; *ROOT = new; printf("ROOOOT = %p\n", new); } int insert_node(struct b_node *ROOT) { struct b_node *cur; struct b_node *new; int key; int error = 0; if (!ROOT) { printf("Please initialize root node\n"); return 0; } printf("Type a new key: "); scanf(" %d", &key); new = init_node(key); if (!new) return 1; cur = ROOT; // printf("new item key = %d\n", new->key); // printf("cur = %p ROOT = %p\n", cur, ROOT); while (1) { if (new->key <= cur->key) { /*go left*/ if (cur->left == NULL) { cur->left = new; break; } else { cur = cur->left; continue; } } else { printf("Current right: %p\n", cur); /*go right*/ if (cur->right == NULL) { cur->right = new; break; } else { cur = cur->right; continue; } } } // printf("KEEP ROOT = %p\n",ROOT); return 0; } int delete_node(struct b_node *ROOT, int key) { } void print_tree(struct b_node *ROOT) { } void print_right(struct b_node *ROOT) { struct b_node *cur; if (ROOT == NULL) { printf ("Tree doesn't exist\n"); return; } cur = ROOT; while (cur) { printf(" Node: %p - Key : %d\n", cur, cur->key); cur = cur->right; } } void print_left(struct b_node *ROOT) { struct b_node *cur; if (ROOT == NULL) { printf ("Tree doesn't exist\n"); return; } cur = ROOT; while (cur) { printf(" Node: %p - Key : %d\n", cur, cur->key); cur = cur->left; } } void usage() { printf("Usage: \n"); printf("a: Alloc root node\n"); printf("i: Insert node\n"); printf("d: Delete node\n"); printf("s: Search node\n"); printf("r: Print the right nodes \n"); printf("l: Print the left nodes \n"); return; } int main(void) { struct b_node *ROOT = NULL; while (1) { char opt; printf(" Option: "); scanf(" %c", &opt); switch(opt) { case 'a': alloc_root(&ROOT); break; case 'i': insert_node(ROOT); break; case 'l': print_left(ROOT); break; case 'r': print_right(ROOT); break; case 'q': goto out; default: usage(); break; } } out: if (ROOT) free(ROOT); return 0; }