Guest User

Untitled

a guest
Sep 12th, 2023
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <exception>
  3. #include <memory>
  4.  
  5.  
  6. struct Node {
  7. Node(int value): value(value) {}
  8. int value;
  9. std::shared_ptr<Node> left = nullptr;
  10. std::shared_ptr<Node> right = nullptr;
  11. };
  12.  
  13.  
  14. struct BinarySearchTree {
  15. std::shared_ptr<Node> root_node = nullptr;
  16. };
  17.  
  18.  
  19. void add(int value, std::shared_ptr<Node> &current) {
  20. if (current == nullptr) {
  21. Node new_node(value);
  22. current = std::make_shared<Node>(new_node);
  23. return;
  24. }
  25.  
  26. if (value < current->value)
  27. add(value, current->left);
  28.  
  29. if (value > current->value)
  30. add(value, current->right);
  31.  
  32. if (value == current->value)
  33. throw std::exception();
  34. }
  35.  
  36.  
  37. int get(int value, std::shared_ptr<Node> &current) {
  38. if (value < current->value)
  39. get(value, current->left);
  40.  
  41. if (value > current->value)
  42. get(value, current->right);
  43.  
  44. return current->value;
  45. }
  46.  
  47.  
  48. int main() {
  49. BinarySearchTree test;
  50. add(8, test.root_node);
  51. add(6, test.root_node);
  52. add(3, test.root_node);
  53.  
  54. std::cout << get(8, test.root_node) << std::endl;
  55.  
  56. return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment