└── binary search tree concepts /binary search tree concepts: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | Node* left; 7 | int key; 8 | Node* right; 9 | }; 10 | Node* newNode(int data){ 11 | Node* n=new Node(); 12 | n->key=data; 13 | n->left=NULL; 14 | n->right=NULL; 15 | return n; 16 | } 17 | Node* insert(Node*root,int data){ 18 | Node* nn=newNode(data); 19 | if(root==NULL){ 20 | root=nn; 21 | return root; 22 | } 23 | else{ 24 | queueq; 25 | q.push(root); 26 | while(!q.empty()){ 27 | Node* present=q.front(); 28 | q.pop(); 29 | if(present->left==NULL && present->key>nn->key){ 30 | present->left=nn; 31 | break; 32 | } 33 | else{ 34 | q.push(present->left); 35 | } 36 | if(present->right==NULL && present->keykey){ 37 | present->right=nn; 38 | break; 39 | } 40 | else{ 41 | q.push(present->right); 42 | } 43 | } 44 | } 45 | return root; 46 | } 47 | Node* minimum(Node* root){ 48 | if(root->left==NULL){ 49 | return root; 50 | } 51 | else 52 | return minimum(root->left); 53 | } 54 | 55 | Node* deleteNode(Node* root,int data){ 56 | if(root==NULL){ 57 | cout<<"Value not found in BST"; 58 | return NULL; 59 | } 60 | if(datakey){ 61 | root->left=deleteNode(root->left,data); 62 | } 63 | else if(data>root->key){ 64 | root->right=deleteNode(root->right,data); 65 | } 66 | else{ 67 | if(root->left!=NULL&&root->right!=NULL){ 68 | Node* temp=root; 69 | Node* minNodeForRight=minimum(temp->right); 70 | root->key=minNodeForRight->key; 71 | root->right=deleteNode(root->right,minNodeForRight->key); 72 | } 73 | else if(root->left!=NULL){ 74 | root=root->left; 75 | } 76 | else if(root->right!=NULL){ 77 | root=root->right; 78 | } 79 | else{ 80 | root=NULL; 81 | } 82 | } 83 | return root; 84 | } 85 | //display function or level order 86 | Node* display(Node* root){ 87 | if(root==NULL){ 88 | cout<<"Tree Empty"; 89 | } 90 | queuequeue; 91 | queue.push(root); 92 | while(!queue.empty()){ 93 | Node*front=queue.front(); 94 | queue.pop(); 95 | cout<key<<"->"; 96 | if(front->left!=NULL){ 97 | queue.push(front->left); 98 | } 99 | if(front->right!=NULL){ 100 | queue.push(front->right); 101 | } 102 | } 103 | cout<<"NULL"; 104 | return root; 105 | } 106 | 107 | Node* search(Node* root, int data) { 108 | if (root == NULL) { 109 | cout << "Not Found "; 110 | return root; 111 | } 112 | else if (root->key == data) { 113 | cout << "Found "; 114 | } else if (root->key>data) { 115 | search(root->left, data); 116 | } else { 117 | root->right=search(root->right, data); 118 | } 119 | } 120 | 121 | 122 | 123 | int main() { 124 | Node* root=NULL; 125 | root=insert(root,54); 126 | root=insert(root,56); 127 | root=insert(root,7); 128 | root=insert(root,2); 129 | root=insert(root,70); 130 | root=insert(root,5); 131 | search(root,7); 132 | root=deleteNode(root,56); 133 | 134 | display(root); 135 | } 136 | --------------------------------------------------------------------------------