fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node {
  5. int val;
  6. Node* left;
  7. Node* right;
  8.  
  9. Node(int x) {
  10. val = x;
  11. left = NULL;
  12. right = NULL;
  13. }
  14. };
  15.  
  16. Node* insert(Node* root, int x) {
  17. if (root == NULL) {
  18. root = new Node(x);
  19. } else if (x < root->val) {
  20. root->left = insert(root->left, x);
  21. } else {
  22. root->right = insert(root->right, x);
  23. }
  24. return root;
  25. }
  26.  
  27. void preorder(Node* root) {
  28. if(root == NULL) return;
  29.  
  30. cout << root->val << " ";
  31. preorder(root->left);
  32. preorder(root->right);
  33. }
  34.  
  35. void inorder(Node* root) {
  36. if(root == NULL) return;
  37.  
  38. inorder(root->left);
  39. cout << root->val << " ";
  40. inorder(root->right);
  41. }
  42.  
  43. void postorder(Node* root) {
  44. if(root == NULL) return;
  45.  
  46. postorder(root->left);
  47. postorder(root->right);
  48. cout << root->val << " ";
  49. }
  50.  
  51. bool find(Node* root, int val) {
  52. if (root == NULL) {
  53. return 0; // Value not found
  54. }
  55. if (root->val == val) {
  56. return 1; // Value found
  57. } else if (val < root->val) {
  58. return find(root->left, val);
  59. } else {
  60. return find(root->right, val);
  61. }
  62. }
  63.  
  64. int main() {
  65. ios_base::sync_with_stdio(0); cin.tie(0);
  66. Node* root = NULL;
  67.  
  68. // Insert elements into BST
  69. root = insert(root, 5);
  70. root = insert(root, 3);
  71. root = insert(root, 7);
  72. root = insert(root, 2);
  73. root = insert(root, 4);
  74. root = insert(root, 6);
  75. root = insert(root, 8);
  76.  
  77. // Print elements of BST in sorted order
  78. cout << "Inorder traversal of BST: ";
  79. inorder(root);
  80. cout << "\n";
  81.  
  82. // Find elements in BST
  83. cout << "Find 3 in BST: " << find(root, 3) << endl; // Output should be 1
  84. cout << "Find 9 in BST: " << find(root, 9) << endl; // Output should be 0
  85.  
  86. return 0;
  87. }
  88.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Inorder traversal of BST: 2 3 4 5 6 7 8 
Find 3 in BST: 1
Find 9 in BST: 0