Last active
July 3, 2019 08:08
-
-
Save manojnaidu619/84d4a1b8c1083d4d5d936ef2b5b3ec76 to your computer and use it in GitHub Desktop.
Binary Search Tree Creation, Searching for key and Deleting leaf node in CPP
This file contains hidden or 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 <iostream> | |
| using namespace std; | |
| struct Node{ | |
| struct Node *lchild; | |
| int data; | |
| struct Node *rchild; | |
| }*root=NULL; | |
| void insert(int key){ | |
| struct Node *p = root,*q=NULL,*temp; | |
| if(root==NULL){ | |
| temp = new Node; | |
| temp->lchild = NULL; | |
| temp->data = key; | |
| temp->rchild = NULL; | |
| root = temp; | |
| }else{ | |
| while(p!=NULL){ | |
| q=p; | |
| if(key < p->data){ | |
| p=p->lchild; | |
| } | |
| else if(key > p->data){ | |
| p=p->rchild; | |
| } | |
| else{ | |
| return; | |
| } | |
| } | |
| temp = new Node; | |
| temp -> data = key; | |
| temp -> rchild=NULL; | |
| temp->lchild = NULL; | |
| if(key > q->data){ | |
| q->rchild = temp; | |
| }else{ | |
| q->lchild = temp; | |
| } | |
| } | |
| } | |
| void Inorder(struct Node *p){ // Inorder traversal prints the BST in Sorted order | |
| if(p){ | |
| Inorder(p->lchild); | |
| cout << p->data << " "; | |
| Inorder(p->rchild); | |
| } | |
| } | |
| void search(int key){ | |
| struct Node *p = root; | |
| while(p != NULL){ | |
| if(p->data == key){ | |
| cout << "Element Found!" << endl; | |
| return; | |
| }else if(key < p->data){ | |
| p=p->lchild; | |
| }else{ | |
| p=p->rchild; | |
| } | |
| } | |
| cout << "Element Not Found!" << endl; | |
| } | |
| void del(int key){ | |
| struct Node *p=root, *q=NULL; | |
| while(p->lchild!=NULL || p->rchild!=NULL){ | |
| q=p; | |
| if(key < p->data){ | |
| p=p->lchild; | |
| }else if(key > p->data){ | |
| p = p->rchild; | |
| } | |
| } | |
| if(p->lchild==NULL && p->rchild==NULL){ // to remove leaf nodes | |
| if(q->data > p->data){ | |
| q->lchild = NULL; | |
| }else{ | |
| q->rchild = NULL; | |
| } | |
| delete p; | |
| } | |
| } | |
| int main(){ | |
| insert(10); | |
| insert(230); | |
| insert(1); | |
| insert(16); | |
| insert(12); | |
| Inorder(root); | |
| cout << endl; | |
| search(16); | |
| search(17); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment