Last active
May 28, 2016 19:18
-
-
Save PsySc0rpi0n/a3650a300c63be1f091cfbb0062d612b to your computer and use it in GitHub Desktop.
binary search tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
typedef struct bstNode { | |
int data; | |
struct bstNode* left; | |
struct bstNode* right; | |
}bstNode; | |
bstNode* GetNewNode (int data); | |
bstNode* insertNode(bstNode* root, int data); | |
bool search_bst (bstNode* root, int data); | |
bstNode* GetNewNode (int data){ | |
bstNode* newNode = NULL; | |
if ((newNode = malloc (sizeof (bstNode))) == NULL){ | |
printf ("Node create error!\n"); | |
exit (-1); | |
} | |
newNode->data = data; | |
newNode->left = NULL, newNode->right = NULL; | |
return newNode; | |
} | |
bstNode* insertNode(bstNode* root, int data){ | |
if (root == NULL) | |
root = GetNewNode (data); | |
else if (data <= root->data) | |
root->left = insertNode (root->left, data); | |
else | |
root->right = insertNode (root->right, data); | |
return root; | |
} | |
bool search_bst (bstNode* root, int data){ | |
if (root == NULL) | |
return false; | |
else if (root->data == data) | |
return true; | |
else if (data <= root->data) | |
return search_bst (root->right, data); | |
else | |
return search_bst (root->left, data); | |
} | |
int main (void){ | |
int value; | |
bstNode* root = NULL; | |
root = insertNode (root, 15); | |
root = insertNode (root, 10); | |
root = insertNode (root, 20); | |
root = insertNode (root, 25); | |
root = insertNode (root, 8); | |
root = insertNode (root, 12); | |
printf ("root: %p\n", (void*) root); | |
printf ("Insert a number to search:\n"); | |
scanf ("%d", &value); | |
if (search_bst (root, value)) | |
printf ("Found!\n"); | |
else | |
printf ("Not found!\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment