commit 3ab98266dcd39b857c1143e54837a12492668908
parent e79063b1323e6e3252943c93f4b58bdd99aac03f
Author: Agastya Chandrakant <acagastya@outlook.com>
Date: Fri, 17 Nov 2017 10:00:39 +0530
Add files via upload
Diffstat:
A | s3/oops/tree.cpp | | | 100 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 100 insertions(+), 0 deletions(-)
diff --git a/s3/oops/tree.cpp b/s3/oops/tree.cpp
@@ -0,0 +1,100 @@
+#include <iostream>
+
+struct node{
+ struct node* left;
+ struct node* right;
+ int data;
+};
+
+class bstree{
+public:
+ node *root;
+ bstree(){
+ root = NULL;
+ }
+ bool isNULL(struct node* r){
+ if(r == NULL)
+ return true;
+ return false;
+ };
+ bool isNULLroot(){
+ if(root == 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(){
+ bstree b;
+ int choice, d;
+ do{
+ printf("Your choice> ");
+ scanf("%d", &choice);
+ switch (choice) {
+ case 1:
+ printf("Enter a number: ");
+ scanf("%d", &d);
+ if(b.isNULLroot()) b.createRoot(d);
+ else b.insert(d, b.root);
+ break;
+ case 2:
+ printf("Enter the element to be searched: ");
+ scanf("%d", &d);
+ printf("%d\n", b.contains(d, b.root));
+ break;
+ case 3:
+ if(b.isNULL(b.root)) printf("Empty tree.\n");
+ else b.printInOrder(b.root);
+ break;
+ case 4:
+ choice = 0;
+ }
+ }while(choice);
+ return 0;
+}