Advertisement
SabirSazzad

Binary Search Tree using Link List

Feb 26th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6.     int data;
  7.     Node *left;
  8.     Node *right;
  9. };
  10. Node *getnewnode(int data)
  11. {
  12.     Node *newnode = new Node();
  13.     newnode->data = data;
  14.     newnode->left = NULL;
  15.     newnode->right = NULL;
  16.  
  17.     return newnode;
  18. }
  19. Node *Insert(Node *root, int data)
  20. {
  21.     if(root==NULL)
  22.     {
  23.         root = getnewnode(data);
  24.     }
  25.     else if(data <= root->data)
  26.     {
  27.         root->left = Insert(root->left,data);
  28.     }
  29.     else
  30.     {
  31.         root->right = Insert(root->right,data);
  32.     }
  33.     return root;
  34. }
  35. void Search(Node *root, int data)
  36. {
  37.     if(root==NULL)
  38.     {
  39.         cout << "Not Found"<<endl;
  40.     }
  41.     else if(root->data == data)
  42.     {
  43.         cout << "Found"<<endl;
  44.     }
  45.     else if(data <= root->data)
  46.     {
  47.         return Search(root->left,data);
  48.     }
  49.     else
  50.     {
  51.         return Search(root->right,data);
  52.     }
  53. }
  54.  
  55. void preorder(Node *root)
  56. {
  57.    if (root==NULL)
  58.    {
  59.        return;
  60.    }
  61.    cout << root->data << " ";
  62.    preorder(root->left);
  63.    preorder(root->right);
  64.  
  65. }
  66. void inorder(Node *root)
  67. {
  68.     if(root == NULL)
  69.     {
  70.         return;
  71.     }
  72.     inorder(root->left);
  73.     cout << root->data << " ";
  74.     inorder(root->right);
  75. }
  76. void postorder(Node *root)
  77. {
  78.     if(root==NULL)
  79.     {
  80.         return;
  81.     }
  82.     postorder(root->left);
  83.     postorder(root->right);
  84.     cout << root->data << " ";
  85. }
  86. int main()
  87. {
  88.     Node *root = NULL;
  89.     int limit,i,data,src;
  90.     cout<< "Input number of data: ";
  91.     cin >> limit;
  92.     for(i=1;i<=limit;i++)
  93.     {
  94.         cout << "Input data: ";
  95.         cin >> data;
  96.         root = Insert(root,data);
  97.     }
  98.     cout << "\nPreorder traversal..."<<endl;
  99.     preorder(root);
  100.     cout << "\nInorder traversal..."<<endl;
  101.     inorder(root);
  102.     cout << "\npostorder traversal..."<<endl;
  103.     postorder(root);
  104.     cout << "\nInput a data for Search: ";
  105.     cin >> src;
  106.     Search(root,src);
  107.  
  108.     return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement