Hydron

BinaryTree with DataPoints

Feb 9th, 2022
810
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. class DataPoint{
  6. public:
  7.     int x, y, z;
  8.     float value;
  9.     DataPoint(int _x = 0, int _y = 0, int _z = 0, float _value = 0)
  10.         {x = _x, y = _y, z = _z, value = _value;}
  11.     bool operator==(DataPoint other){
  12.         return (x == other.x && y == other.y && z == other.z && value == other.value);
  13.     }
  14.     bool operator<(DataPoint other){
  15.         return (x < other.x);
  16.     }
  17. };
  18.  
  19. int BAD_ADRESS = -1;
  20.  
  21. class Tree{
  22. private:
  23.     class TreeNode{
  24.     public:
  25.         DataPoint content;
  26.         TreeNode *lft, *rght;
  27.         TreeNode(DataPoint _content = DataPoint())
  28.             {lft = rght = nullptr, content = _content;}
  29.     } *root;
  30. public:
  31.     Tree():
  32.         root(nullptr)
  33.         {}
  34.     void add_element(DataPoint _content){
  35.         if (root == nullptr) {root = new TreeNode(_content); return;}
  36.         TreeNode *cur = root;
  37.         while(cur != nullptr){
  38.             if (cur->content < _content){
  39.                 if (cur->rght == nullptr) {cur->rght = new TreeNode(_content); break;}
  40.                 else cur = cur->rght;
  41.             }else{
  42.                 if (cur->lft == nullptr) {cur->lft = new TreeNode(_content); break;}
  43.                 else cur = cur->lft;
  44.             }
  45.         }
  46.     }
  47.     DataPoint get_root(){
  48.         return root->content;
  49.     }
  50.     void *find_element(DataPoint _element){
  51.         TreeNode *cur = root;
  52.         while(cur != nullptr){
  53.             if (cur->content == _element) return &(cur->content);
  54.             if (cur->content < _element) cur = cur->rght;
  55.             else cur = cur->lft;
  56.         }
  57.         return &BAD_ADRESS;
  58.     }
  59. };
  60.  
  61. int main(){
  62.     DataPoint a(1, 1, 1, 1);
  63.     Tree *t = new Tree();
  64.     t->add_element(a);
  65.     a = DataPoint(1, 2, 2, 2);
  66.     t->add_element(a);
  67.     void *answer = t->find_element(a);
  68.     if (*static_cast<int*> (answer) == -1) cout << "Error: Not found!\n";
  69.     else{
  70.         DataPoint x = *static_cast<DataPoint*> (answer);
  71.         cout << "{" << x.x << ' ' << x.y << ' ' << x.z << ' ' << x.value << "} was successfully found!\n";
  72.     }
  73.     return 0;
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment