ProAnswers.org

algorithm Insert a node in a Binary Search Tree

algorithm Insert a node in a Binary Search Tree

typedef struct node{

	    int data;

	    struct node *left, *right;

	}node;

	 

	node *insert(node *root,node *newnode){

	    node *y;

	    node *temp;

	    y = NULL;

	    temp = root;

	    while(temp != NULL){

	        y = temp;

	        if(newnode -> data < root -> data)

	            temp = temp -> left;

	        else temp = temp -> right;

	    }

	    if(y == NULL){

	        root = newnode;

	        return root;

	    }

	    else{

	        if(newnode->data < y->data)

	            y -> left = newnode;

	        else y -> right = newnode;

	    }

	    return root;

	}