commit e79063b1323e6e3252943c93f4b58bdd99aac03f
parent fc2ebfb72c3b21be29a150e267274f7b1ce97433
Author: Agastya Chandrakant <acagastya@outlook.com>
Date: Fri, 17 Nov 2017 09:51:32 +0530
bst but in C
Diffstat:
A | s3/oops/bst.c | | | 94 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 94 insertions(+), 0 deletions(-)
diff --git a/s3/oops/bst.c b/s3/oops/bst.c
@@ -0,0 +1,94 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+struct node{
+ struct node* left;
+ struct node* right;
+ int data;
+} *root;
+
+bool isNULL(struct node* r){
+ if(r == NULL)
+ return true;
+ return false;
+}
+
+void createRoot(int data) {
+ root = (struct node*)malloc(sizeof(struct node));
+ if(isNULL(root)){
+ printf("Insufficient memory.\n");
+ return;
+ }
+ root->data = data;
+ root->left = root->right = NULL;
+}
+
+struct node* getnode(int data){
+ struct node* temp = (struct node *)malloc(sizeof(struct node));
+ if(isNULL(temp))
+ printf("Insufficient memory.\n");
+ else{
+ temp->left = temp->right = NULL;
+ temp->data = data;
+ }
+ return temp;
+}
+
+void insert(int data, struct node* parent){
+ if(data < parent->data)
+ if(!isNULL(parent->left))
+ insert(data, parent->left);
+ else parent->left = getnode(data);
+ else
+ if(!isNULL(parent->right))
+ insert(data, parent->right);
+ else parent->right = getnode(data);
+}
+
+bool contains(int data, struct node *parent){
+ if(isNULL(parent))
+ return false;
+ if(parent->data == data)
+ return true;
+ if(data < parent->data)
+ return contains(data, parent->left);
+ if(data > parent->data)
+ return contains(data, parent->right);
+}
+
+void printInOrder(struct node* parent){
+ if(!isNULL(parent->left))
+ printInOrder(parent->left);
+ printf("%d ", parent->data);
+ if(!isNULL(parent->right))
+ printInOrder(parent->right);
+}
+
+int main(){
+ int choice, d;
+ do{
+ printf("Your choice> ");
+ scanf("%d", &choice);
+ switch (choice) {
+ case 1:
+ printf("Enter a number: ");
+ scanf("%d", &d);
+ if(isNULL(root)) createRoot(d);
+ else insert(d, root);
+ break;
+ case 2:
+ printf("Enter the element to be searched: ");
+ scanf("%d", &d);
+ printf("%d\n", contains(d, root));
+ break;
+ case 3:
+ if(isNULL(root)) printf("Empty tree.\n");
+ else printInOrder(root);
+ break;
+ case 4:
+ choice = 0;
+ }
+ }while(choice);
+ return 0;
+}