fork download
  1. //
  2. // main.cpp
  3. // Binary Search Tree (Basic)
  4. //
  5. // Created by Himanshu on 16/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. struct node {
  12. int info = 0;
  13. struct node *left, *right;
  14. };
  15. typedef struct node Node;
  16.  
  17. node* newNode(int data)
  18. {
  19. node* Node = new node();
  20. Node->info = data;
  21. Node->left = NULL;
  22. Node->right = NULL;
  23.  
  24. return(Node);
  25. }
  26.  
  27. Node* insert (Node *root, int n) {
  28. if (root == NULL) {
  29. root = newNode(n);
  30. } else {
  31. if (root->info > n) {
  32. root->left = insert (root->left, n);
  33. } else {
  34. root->right = insert (root->right, n);
  35. }
  36. }
  37. return root;
  38. }
  39.  
  40. Node* search (Node *root, int n) {
  41. if (root == NULL || root->info == n) {
  42. return root;
  43. } else {
  44. if (root->info > n) {
  45. return search (root->left, n);
  46. } else {
  47. return search (root->right, n);
  48. }
  49. }
  50. }
  51.  
  52. int main() {
  53. Node *root = newNode(5);
  54. insert(root, 3);
  55. insert(root, 2);
  56. insert(root, 4);
  57. insert(root, 7);
  58.  
  59. //Searching 4 in the tree
  60. if (search (root, 4)) {
  61. cout<<"4 is present in the BST"<<endl;
  62. } else {
  63. cout<<"4 is not in the BST"<<endl;
  64. }
  65.  
  66. //Searching 8 in the tree
  67. if (search (root, 8)) {
  68. cout<<"8 is present in the BST"<<endl;
  69. } else {
  70. cout<<"8 is not in the BST"<<endl;
  71. }
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.01s 5348KB
stdin
Standard input is empty
stdout
4 is present in the BST
8 is not in the BST