c - Implementing a binary search tree -
i'm trying implement binary search tree holds inventory of ordered stock. stocked item attributes stored in nodes such:
typedef struct item item_t; struct item{ char name; int price; int quantity; item_t *left; item_t *right; };
the idea prompt user enter above attributes, , add entered item node. i've written far:
item_t *root = null; item_t *current_leaf = null; void prompt_user(){ /* in here contains code prompts user item attributes , stores in variable called input */ insert_node(input); } void insert_node(char *input){ /*if tree doesnt have root...*/ if (root == null){ /*create one...*/ *root = create_node(input); } else{ item_t *cursor = root; item_t *prev = null; int is_left = 0; int comparison; while(cursor != null){ /*comparison 1 key of input less key of cursor, , 2 otherwise...*/ comparison = compare(input, cursor); prev = cursor; if(comparison == 1){ is_left = 1; cursor = cursor->left; } else if (comparison == 2){ is_left = 0; cursor = cursor->right; } } if(is_left){ *prev->left = create_node(input); current_leaf = prev->left; } else{ *prev->right = create_node(input); current_leaf = prev->right; } } } item_t create_node(char *input){ item_t *new_node = (item_t*)malloc(sizeof(item_t)); if (new_node == null){ printf("out of memory. shutting down.\n"); exit(exit_failure); } /*add data node...*/ update_item(input, new_node); new_node->left = null; new_node->right = null; current_leaf = new_node; return *new_node; }
i want root
pointing first item ever entered, , current_leaf
pointing last item processed. compare
returns 1 if item being processed (input
) less last processed item (current_leaf
). update_item
sets data new nodes (leaves).
the above isn't complete, it's i'm @ moment. i'm struggling work out how write add_node
, how keep current_leaf
updated correctly.
edit: revised code
it example of bst. structure of tree is:
typedef struct node{ int data; struct node *left, *right; }node;
letting root global not idea, better declare inside main()
, insert()
called main this:
int main() { int n,data; node *root=null; printf("how many elements? "); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&data); insert(&root,data); } inorder(root); return 0; }
this code insertion , traversing binary tree-
void insert(node **root, int data) { node *n1,*temp; n1=(node *)malloc(sizeof(node)); n1->data=data; n1->left=n1->right=null; if(!(*root)) { (*root)=n1; //printf("node inserted\n"); return; } temp=*root; while(temp!=null) { if(temp->data<temp->data) { //printf("to right"); if(temp->right==null) { temp->right=n1; break; } else temp=temp->right; } else if(temp->data>=n1->data) { if(temp->left==null) { temp->left=n1; break; } else temp=temp->left; } } //printf("inserted\n"); } void inorder(node *root) { if(root==null) return; inorder(root->left); printf("item: %d",root->data); inorder(root->right); }
the searching same same logic insert, please develop yourself.
Comments
Post a Comment