Advertisement
pasholnahuy

Глубина добавляемых элементов

May 28th, 2023
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <tuple>
  6. #include <set>
  7. #include <map>
  8. #include <unordered_map>
  9.  
  10. using namespace std;
  11.  
  12. class BST {
  13.     struct Node {
  14.         int key;
  15.         int depth;
  16.         Node *l = nullptr, *r = nullptr;
  17.         explicit Node(int key) : key(key) {}
  18.     }
  19.             *root = nullptr;
  20.  
  21.     bool contains(Node *n, int key) const {
  22.         if (!n) {
  23.             return false;
  24.         } else if (key == n->key) {
  25.             return true;
  26.         } else if (key > n->key) {
  27.             return contains(n->r, key);
  28.         } else {
  29.             return contains(n->l, key);
  30.         }
  31.     }
  32.  
  33.     void insert(Node *n, int key) {
  34.         if (!root) {
  35.             root = new Node(key);
  36.             return;
  37.         }
  38.         if (key == n->key) {
  39.             return;
  40.         }
  41.         if (key < n->key) {
  42.             if (n->l) {
  43.                 insert(n->l, key);
  44.             } else {
  45.                 n->l = new Node(key);
  46.             }
  47.  
  48.         } else {
  49.             if (n->r) {
  50.                 insert(n->r, key);
  51.             } else {
  52.                 n->r = new Node(key);
  53.             }
  54.         }
  55.     }
  56.     void MakeDepth(Node *n, int cur_depth){
  57.         if (n == nullptr){
  58.             return;
  59.         }
  60.         n->depth = cur_depth;
  61.         depths[n->key] = n->depth;
  62.         MakeDepth(n->l, cur_depth+1);
  63.         MakeDepth(n->r, cur_depth+1);
  64.  
  65.     };
  66.  
  67. public:
  68.     map<int, int> depths;
  69.     bool contains(int key) const {
  70.         return contains(root, key);
  71.     }
  72.  
  73.     void insert(int key) {
  74.         return insert(root, key);
  75.     }
  76.  
  77.     void MakeDepth(){
  78.         return MakeDepth(root, 1);
  79.     }
  80. };
  81.  
  82. int main() {
  83.     int n = -1;
  84.     BST tree;
  85.     vector<int> vec;
  86.     while (n != 0) {
  87.         cin >> n;
  88.         if (n != 0) {
  89.             vec.emplace_back(n);
  90.             tree.insert(n);
  91.         }
  92.     }
  93.     tree.MakeDepth();
  94.     for (auto el: vec){
  95.         cout << tree.depths[el] << " ";
  96.     }
  97.     return 0;
  98. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement