Skip to content

Instantly share code, notes, and snippets.

@abhiksark
Last active February 1, 2017 10:30
Show Gist options
  • Save abhiksark/5700f3c737f143667b2887584a4e9f25 to your computer and use it in GitHub Desktop.
Save abhiksark/5700f3c737f143667b2887584a4e9f25 to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include<stdlib.h>
struct tree{
int data;
struct tree *left;
struct tree *right;
};
struct tree *head = NULL;
struct tree *newTree(int input){
struct tree *temp = (struct tree *)malloc(sizeof(struct tree));
temp->data = input;
temp->left = NULL;
temp->right=NULL;
return temp;
}
void insert(int input){
struct tree *temp = newTree(input);
struct tree *temp_Head= head;
if (temp_Head==NULL){
head = temp;
return;
}
while(temp_Head){
if( temp_Head->data >= temp->data){
if(!(temp_Head->left)){
temp_Head->left = temp;
break;
}
else{
temp_Head=temp_Head->left;
}
}
else {
if(!(temp_Head->right)){
temp_Head->right = temp;
break;
}
else{
temp_Head=temp_Head->right;
}
}
}
}
void inorderTravel(struct tree *head){
struct tree *temp_Head= head;
if (temp_Head != NULL)
{
inorderTravel(temp_Head->left);
printf("%d \t", temp_Head->data);
inorderTravel(temp_Head->right);
}
}
int findElement(int element){
struct tree *temp_Head= head;
if(temp_Head == NULL) return 0;
while(temp_Head){
if(temp_Head->data == element){
printf("%d",element);
return 1;
}
if(temp_Head->data > element){
temp_Head=temp_Head->left;
}
if(temp_Head->data < element){
temp_Head = temp_Head->right;
}
}
return 0;
}
int main(){
//head=insertTest(head,40);
insert(4);
insert(2);
insert(6);
insert(4);
insert(2);
insert(-6);
inorderTravel(head);
if (findElement(6)) printf("Found");
else printf("Not Found");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment