Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary search tree #1033

Open
KAWALMEET-SINGH opened this issue Feb 15, 2022 · 0 comments
Open

Binary search tree #1033

KAWALMEET-SINGH opened this issue Feb 15, 2022 · 0 comments

Comments

@KAWALMEET-SINGH
Copy link

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

struct node
{
int data;
struct node *l;
struct node *r;
};

struct node* CN(int data)
{
struct node n;
n=(struct node
)malloc(sizeof(struct node));
n->data=data;
n->l=NULL;
n->r=NULL;
return n;
}
void preorder(struct node *root)
{
if(root!=NULL)
{
printf("%d",root->data);
preorder(root->l);
preorder(root->r);

}

}

void postorder(struct node *root)
{
if(root!=NULL)
{
postorder(root->l);
postorder(root->r);
printf("%d",root->data);

}

}

void inorder(struct node *root)
{
if(root!=NULL)
{
inorder(root->l);
printf("%d",root->data);
inorder(root->r);

}

}

int isBST(struct node* root){
static struct node *prev = NULL;
if(root!=NULL){
if(!isBST(root->l)){
return 0;
}
if(prev!=NULL && root->data <= prev->data){
return 0;
}
prev = root;
return isBST(root->r);
}
else{
return 1;
}
}

struct node * searchIter(struct node* root, int key){
while(root!=NULL){
if(key == root->data){
return root;
}
else if(keydata){
root = root->l;
}
else{
root = root->r;
}
}
return NULL;
}

void insert(struct node *root, int key){
struct node prev = NULL;
while(root!=NULL){
prev = root;
if(key==root->data){
printf("Cannot insert %d, already in BST", key);
return;
}
else if(keydata){
root = root->l;
}
else{
root = root->r;
}
}
struct node
new = CN(key);
if(keydata){
prev->l= new;
}
else{
prev->r= new;
}

}

int main(){

struct node *p = CN(5);
 struct node *q = CN(6);
  struct node *r = CN(4);
  p->l=r;
  p->r=q;
insert(p,15);
insert(p,14);
insert(p,2);
insert(p,8);
insert(p,69);

preorder(p);
printf("\n");
inorder(p);
 printf("\n");
postorder(p);
 printf("\n");
if(isBST(p))
{
    printf(" binary search tree");
}
 printf("\n \n kawalmeet singh \n \n  ");

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant