Raslboyy

764

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