SkrillexOMG

BST

Apr 16th, 2022
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct BstNode
  5. {
  6.     int data;
  7.  
  8.     BstNode* left;
  9.  
  10.     BstNode* right;
  11. };
  12.  
  13. BstNode* root;
  14.  
  15. BstNode* GetNewNode(int data)
  16. {
  17.     BstNode* NewNode = new BstNode();
  18.  
  19.     NewNode->data = data;
  20.  
  21.     NewNode->left = NULL;
  22.  
  23.     NewNode->right = NULL;
  24.  
  25.     return NewNode;
  26. }
  27.  
  28. void PreOrder(BstNode* root)
  29.  
  30. {
  31.     if (root == NULL)
  32.  
  33.     {
  34.         return;
  35.     }
  36.  
  37.     cout << root->data << " ";
  38.  
  39.     PreOrder(root->left);
  40.  
  41.     PreOrder(root->right);
  42. }
  43.  
  44. BstNode* Insert(BstNode* root, int data)
  45.  
  46. {
  47.     if (root == NULL)
  48.  
  49.     {
  50.         root = GetNewNode(data);
  51.     }
  52.  
  53.     else if (data <= root->data)
  54.  
  55.     {
  56.         root->left = Insert(root->left, data);
  57.     }
  58.  
  59.     else
  60.  
  61.     {
  62.         root->right = Insert(root->right, data);
  63.     }
  64.  
  65.     return root;
  66. }
  67.  
  68. bool Search(BstNode* root, int data)
  69.  
  70. {
  71.     if (root == NULL)
  72.  
  73.     {
  74.         cout << "Error: tree is empty" << endl;
  75.  
  76.         return false;
  77.     }
  78.  
  79.     else if (root->data == data)
  80.  
  81.     {
  82.         return true;
  83.     }
  84.  
  85.     else if (data <= root->data)
  86.  
  87.     {
  88.         return Search(root->left, data);
  89.     }
  90.  
  91.     else
  92.  
  93.     {
  94.         return Search(root->right, data);
  95.     }
  96. }
  97.  
  98. int main()
  99.  
  100. {
  101.     root = NULL;
  102.  
  103.     root = Insert(root, 5);
  104.  
  105.     root = Insert(root, 6);
  106.  
  107.     root = Insert(root, 4);
  108.  
  109.     root = Insert(root, 7);
  110.  
  111.     root = Insert(root, 3);
  112.  
  113.     root = Insert(root, 2);
  114.  
  115.     cout << "please enter your search item: ";
  116.  
  117.     int s;
  118.  
  119.     cin >> s;
  120.  
  121.     cout << endl;
  122.  
  123.     if (Search(root, s) == true)
  124.     {
  125.         cout << "found" << endl;
  126.     }
  127.  
  128.     else
  129.     {
  130.         cout << "Not found" << endl;
  131.     }
  132.  
  133.     PreOrder(root);
  134. }
Advertisement
Add Comment
Please, Sign In to add comment