From 3fd153b2ad4b705523acb63e326516327dabcb28 Mon Sep 17 00:00:00 2001 From: GothamK <43772245+GothamK@users.noreply.github.com> Date: Thu, 14 Oct 2021 21:15:09 +0530 Subject: [PATCH] Binary Search Tree alternate implementation --- .../BST/BST_updated_implementation | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 C++/Data-Structures/BST/BST_updated_implementation diff --git a/C++/Data-Structures/BST/BST_updated_implementation b/C++/Data-Structures/BST/BST_updated_implementation new file mode 100644 index 00000000..26bc4a18 --- /dev/null +++ b/C++/Data-Structures/BST/BST_updated_implementation @@ -0,0 +1,155 @@ +/*input + +*/ + +#include +#define dbg(x) cout << #x << " = " << x << '\n' + +using namespace std; + +struct Node +{ + int data; + struct Node* left = NULL; + struct Node* right = NULL; +}; +struct Node* r1; + + +bool find(int x, struct Node*curr) +{ + + if(!curr) return 0; + else if(curr->data == x) + { + cout<left == NULL && curr->right == NULL) + { + cout<data > x) + { + return find(x,curr->left); + } + else if (curr->data < x) + { + return find(x,curr->right); + } +} + +void insert(int x, struct Node* newNode) +{ + struct Node* curr = r1; + if(curr == NULL) + { + r1 = newNode; + cout<data) + { + if(curr->left == NULL) + { + curr->left = newNode; + } + curr = curr->left; + } + else if(x > curr->data) + { + if(curr->right == NULL) + { + curr->right = newNode; + } + curr = curr->right; + } + else break; + } + cout<data > x) delete(x,curr->left); + else if(curr->data < x) delete(x,curr->right); + else if(curr->data == x) + { + + if(curr->left != NULL && curr->right != NULL) + { + struct Node* mx = maxNode(curr->left); + curr->data = mx->data; + root->left = delete(curr->data, curr->left); + + } + else + { + + } + } + else + { + cout<left != NULL) inorder(curr->left); + cout<data<<" "; + if(curr->right != NULL) inorder(curr->right); +} + + +signed main() +{ + int n,t; + while(1) + { + cin>>n; + if(n==1) + { + cout<<"Number to Insert: "; + cin>>t; + struct Node *newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->left = NULL; + newNode->right = NULL; + newNode->data = t; + insert(t,newNode); + } + else if(n==2) + { + cout<<"Number to Find: "; + cin>>t; + struct Node* curr = r1; + find(t, curr); + } + else if(n==3) + { + struct Node* curr = r1; + inorder(curr); + cout<<"\nInorder Traversal Finished\n"; + } + else if(n==4) + { + } + else break; + } + + return 0; +}