Left Node ROOT Right Node

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Left node<=ROOT<Right Node

#include<stdio.h>
#include<stdlib.h>

struct node{
int data;
struct node *lchild, *rchild;
};

struct node *root = NULL;

void createBST(){
int n;
struct node *temp, *trav;
temp = (struct node*)malloc(sizeof(struct
node));
printf("\nEnter the key value (data part) of the
new node: ");
scanf("%d", &n);

temp->data = n;
temp->lchild = NULL;
temp->rchild = NULL;

if( root == NULL )


{
root = temp;
return;
}

trav = root;
while( 1 ){

if( n < trav->data && trav->lchild != NULL )


trav = trav->lchild;

else if (n > trav->data && trav->rchild !=


NULL )
trav = trav->rchild;
else if( n < trav->data && trav->lchild ==
NULL ){
trav->lchild = temp;
return;
}
else {
trav->rchild = temp;
return;
}
}
}
struct node *search(int x, struct node *trav ){

if( trav == NULL )


return NULL;

else if ( trav->data == x )
return trav;

else if ( x < trav->data )


search(x, trav->lchild);

else
search(x, trav->rchild);

void inorder(struct node *trav){

if( trav != NULL ){


inorder(trav->lchild);
printf("%d, ", trav->data);
inorder(trav->rchild);
}
}

void check( struct node *s){

if( s != NULL )
printf("\nThe node %d is in the BST...", s-
>data);
else
printf("\nThe node is not in the BST....");

void main(){

for (int i=0 ; i<10 ; i++)


createBST();

inorder(root);

struct node *s = search(14, root);


check(s);

s = search(20, root);
check(s);
}

You might also like