Inserting in Binary Search Tree (C) using for loop -
i'm having trouble inserting in binary search tree using loop, when call inordertraversal function, there no output blank line, far think rest of code okay problem in insert function.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct binarytree{ int data; struct binarytree *left; struct binarytree *right; } node; node* insert(node* head, int value) { _bool flag = true; for(node *temp = head; flag == true; (temp = (value >= temp->data)?(temp->right):(temp->left))) { if(temp == null) { temp = (node*)malloc(sizeof(node*)); temp->data = value; temp->left = null; temp->right = null; flag = false; } } return head; } void inordertraversal(node* head) { if(head == null) { return; } inordertraversal(head->left); printf("%d ",head->data); inordertraversal(head->right); } int main(void) { node *head = null; for(int = 0; < 40; i++) { head = insert(head,i); } inordertraversal(head); return 0; }
here try these changes in insert function
node* insert(node *head, int value) { if(!head) //explicitly insert head if null { head = malloc(sizeof *head); head->data = value; head->left = null; head->right = null; return head; } for(node *temp = head,*temp2 = head; ;(temp = (value >= temp->data)?(temp->right):(temp->left))) { if(temp == null) { temp = malloc(sizeof *temp); temp->data = value; temp->left = null; temp->right = null; if(value >= temp2->data) //update previous nodes left or right pointer accordingly temp2->right = temp; else temp2->left = temp; break; } temp2 = temp; //use pointer store previous value of node } return head; }
Comments
Post a Comment