Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- typedef struct Node
- {
- int data;
- struct Node *prev, *next;
- } node;
- node *root = NULL;
- node* newNode(int);
- node* insertNode(node*,int);
- node* searchNode(node*,int);
- void Preorder(node*);
- void inorder(node*);
- void Postorder(node*);
- int main(void)
- {
- int choice,chooseRootNode;
- node* result ;
- cout<<"Enter root node for binary search tree : ";
- cin>>chooseRootNode;
- root = insertNode(root,chooseRootNode);
- while(true)
- {
- cout<<"Menu : 1)Insert 2)Search 3)Pre-Order 4)In-Order 5)Post-Order 6)Exit"<<endl;
- cout<<"Enter your choice : ";
- cin>>choice;
- switch(choice)
- {
- case 1:
- cout<<"Enter (int) data to insert : ";
- int chooseData1;
- cin>>chooseData1;
- insertNode(root,chooseData1);
- break;
- case 2:
- cout<<"Enter (int) data to search : ";
- int chooseData2;
- cin>>chooseData2;
- // very special waring : result cannot be declared inside switch
- // as it is a pointer type variable
- result = searchNode(root,chooseData2);
- if(result!=NULL)
- {
- cout<<"Found"<<endl;
- }
- else
- {
- cout<<"Not found"<<endl;
- }
- break;
- case 3:
- cout<<"Pre-Order : "<<endl;
- Preorder(root);
- cout<<endl;
- break;
- case 4:
- cout<<"In-Order : "<<endl;
- inorder(root);
- cout<<endl;
- break;
- case 5:
- cout<<"Post-Order : "<<endl;
- Postorder(root);
- cout<<endl;
- break;
- case 6:
- return 0;
- break;
- default:
- cout<<"Wrong selection"<<endl;
- break;
- }
- }
- return 0;
- }
- node* newNode(int item)
- {
- node *temp = new node();
- temp->data = item;
- temp->prev = temp->next = NULL;
- return temp;
- }
- node* insertNode(node* node, int data)
- {
- if (node == NULL)
- {
- return newNode(data);
- }
- if (data < node->data)
- {
- node->prev = insertNode(node->prev, data);
- }
- else if (data > node->data)
- {
- node->next = insertNode(node->next, data);
- }
- return node;
- }
- node* searchNode(node* root, int data)
- {
- if (root == NULL || root->data == data)
- {
- return root;
- }
- if (root->data < data)
- {
- return searchNode(root->next, data);
- }
- return searchNode(root->prev, data);
- }
- void Postorder(node* node)
- {
- if (node == NULL)
- {
- return;
- }
- Postorder(node->prev);
- Postorder(node->next);
- cout<<node->data<<" ";
- }
- void Preorder(node* node)
- {
- if (node == NULL)
- {
- return;
- }
- cout<<node->data<<" ";
- Preorder(node->prev);
- Preorder(node->next);
- }
- void inorder(node *root)
- {
- if (root != NULL)
- {
- inorder(root->prev);
- cout<<root->data<<" ";
- inorder(root->next);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement