Advertisement
Raslboyy

765

Oct 3rd, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. struct Node
  7. {
  8.     Node* l;
  9.     Node* r;
  10.     int val;
  11.     int count;
  12.     Node(int val) :val(val), l(nullptr), r(nullptr), count(1) {};
  13. };
  14.  
  15. Node *root = nullptr;
  16. ifstream fin("input.txt");
  17. ofstream fout("output.txt");
  18.  
  19. void add(int val, Node* cur) {
  20.     if (cur == nullptr) {
  21.         root = new Node(val);
  22.         return;
  23.     }
  24.     if (val < cur->val) {
  25.         if (cur->l == nullptr) {
  26.             cur->l = new Node(val);
  27.             return;
  28.         }
  29.         add(val, cur->l);
  30.     }
  31.     else if (val > cur->val) {
  32.         if (cur->r == nullptr) {
  33.             cur->r = new Node(val);
  34.             return;
  35.         }
  36.         add(val, cur->r);
  37.     }
  38.     else
  39.         cur->count++;
  40.  
  41. }
  42.  
  43. void print(Node* cur) {
  44.     if (cur == nullptr) return;
  45.     print(cur->l);
  46.     fout << cur->val << " " << cur->count << "\n";
  47.     print(cur->r);
  48. }
  49.  
  50. int main() {
  51.  
  52.     int a; fin >> a;
  53.     while (a != 0) {
  54.         add(a, root);
  55.         fin >> a;
  56.     }
  57.     print(root);
  58.  
  59.     fin.close();
  60.     fout.close();
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement