|
| 1 | +#include <iostream> |
| 2 | +#include <cstdlib> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +struct node { |
| 6 | + int data; |
| 7 | + struct node *left, *right; |
| 8 | +}; |
| 9 | + |
| 10 | +// Create a node |
| 11 | +struct node *createnode(int item) { |
| 12 | + struct node *temp = (struct node *)malloc(sizeof(struct node)); |
| 13 | + temp->data = item; |
| 14 | + temp->left = temp->right = NULL; |
| 15 | + return temp; |
| 16 | +} |
| 17 | +void inorder(struct node *root) { |
| 18 | + if (root != NULL) { |
| 19 | + inorder(root->left); |
| 20 | + cout << root->data << " "; |
| 21 | + inorder(root->right); |
| 22 | + } |
| 23 | +} |
| 24 | +int search(struct node *root, int key){ |
| 25 | + struct node *prev = NULL; |
| 26 | + while(root!=NULL){ |
| 27 | + prev = root; |
| 28 | + if(key==root->data){ |
| 29 | + printf("Cannot insert %d, already in BST", key); |
| 30 | + return 1; |
| 31 | + } |
| 32 | + else if(key<root->data){ |
| 33 | + root = root->left; |
| 34 | + } |
| 35 | + else{ |
| 36 | + root = root->right; |
| 37 | + } |
| 38 | + } |
| 39 | + return 0; |
| 40 | +} |
| 41 | +struct node *insert(struct node *node, int key) { |
| 42 | +if(search(node,key)==0){ |
| 43 | + |
| 44 | + if (node == NULL){ |
| 45 | + return createnode(key); |
| 46 | +} |
| 47 | + if (key < node->data){ |
| 48 | + node->left = insert(node->left, key); |
| 49 | +} |
| 50 | + else{ |
| 51 | + node->right = insert(node->right, key); |
| 52 | +} |
| 53 | +} |
| 54 | + |
| 55 | + return node; |
| 56 | +} |
| 57 | + |
| 58 | + |
| 59 | +int main() { |
| 60 | + struct node *root = NULL; |
| 61 | + int ch; |
| 62 | + int x; |
| 63 | + cout<<"Press 0 to exit else enter 1: "; |
| 64 | + cin>>ch; |
| 65 | + while(ch!=0) |
| 66 | + { |
| 67 | + cout<<"\n"<<"1.Insertion"<<"\n"<<"2.View"<<"\n"; |
| 68 | + cout<<"\n"<<"Enter choice :"; |
| 69 | + cin>>ch; |
| 70 | + switch (ch) |
| 71 | + { |
| 72 | + case 1: |
| 73 | + cout<<"Enter the value you want to insert in binary search tree: "; |
| 74 | + cin>>x; |
| 75 | + root = insert(root, x); |
| 76 | + break; |
| 77 | + case 2: |
| 78 | + cout << "Inorder traversal: "; |
| 79 | + inorder(root); |
| 80 | + break; |
| 81 | + |
| 82 | + default: |
| 83 | + printf("\nINVALID CHOICE !!"); |
| 84 | + break; |
| 85 | + } |
| 86 | + } |
| 87 | +return 0; |
| 88 | + |
| 89 | + |
| 90 | +} |
0 commit comments