fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node {
  5. int key;
  6. Node* left;
  7. Node* right;
  8. Node(int k) : key(k), left(nullptr), right(nullptr) {}
  9. };
  10.  
  11. Node* insert(Node* root, int key) {
  12. if (!root) return new Node(key);
  13. if (key < root->key) root->left = insert(root->left, key);
  14. else if (key > root->key) root->right = insert(root->right, key);
  15. return root;
  16. }
  17.  
  18. Node* searchRecursive(Node* root, int target) {
  19. if (!root || root->key == target) return root;
  20. return target < root->key ? searchRecursive(root->left, target) : searchRecursive(root->right, target);
  21. }
  22.  
  23. Node* searchIterative(Node* root, int target) {
  24. Node* cur = root;
  25. while (cur) {
  26. if (cur->key == target) return cur;
  27. cur = target < cur->key ? cur->left : cur->right;
  28. }
  29. return nullptr;
  30. }
  31.  
  32. int main() {
  33. Node* root = nullptr;
  34. int num;
  35.  
  36. cout << "Введите элементы дерева (0 для завершения): ";
  37. while (cin >> num && num != 0) {
  38. root = insert(root, num);
  39. }
  40.  
  41. int target;
  42. cout << "Введите число для поиска: ";
  43. cin >> target;
  44.  
  45. cout << (searchRecursive(root, target) ? "Recursive: Found" : "Recursive: Not found") << endl;
  46. cout << (searchIterative(root, target) ? "Iterative: Found" : "Iterative: Not found") << endl;
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 5316KB
stdin
10 20 40 50 60
10
stdout
Введите элементы дерева (0 для завершения): Введите число для поиска: Recursive: Not found
Iterative: Not found