Skip to content

Instantly share code, notes, and snippets.

@toboqus
Created November 5, 2015 20:14
Show Gist options
  • Save toboqus/fa1ec8b706929e7357fe to your computer and use it in GitHub Desktop.
Save toboqus/fa1ec8b706929e7357fe to your computer and use it in GitHub Desktop.
Binary Search Tree in C
/*
* Tree.c
*
* Created on: 5 Nov 2015
* Author: Alex
*/
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node* left;
struct node* right;
};
struct node* newNode(int val){
struct node* tmp = malloc(sizeof(struct node));
tmp->left = NULL;
tmp->right = NULL;
tmp->val = val;
return tmp;
}
struct node* insert(struct node* node, int val){
if(node == NULL){
return newNode(val);
}else{
if(val <= node->val){
node->left = insert(node->left, val);
}else{
node->right = insert(node->right, val);
}
return node;
}
}
int lookup(struct node* node, int val){
if(node == NULL){
return 0;
}else{
if(node->val == val){
return 1;
}
if(val < node->val){
return lookup(node->left, val);
}else{
return lookup(node->right, val);
}
}
}
int main(){
struct node* root = NULL;
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 7);
root = insert(root, 2);
root = insert(root, 1);
if(lookup(root, 7)){
printf("exists");
}else{
printf("does not exist");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment