Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <algorithm>
- using namespace std;
- struct Node {
- Node* l;
- Node* r;
- int val;
- Node(int val) :val(val), l(nullptr), r(nullptr) {};
- };
- Node* root = nullptr;
- void add(int val, Node* cur) {
- if (cur == nullptr) {
- root = new Node(val);
- return;
- }
- if (val < cur->val) {
- if (cur->l == nullptr) {
- cur->l = new Node(val);
- return;
- }
- add(val, cur->l);
- }
- else if (val > cur->val) {
- if (cur->r == nullptr) {
- cur->r = new Node(val);
- return;
- }
- add(val, cur->r);
- }
- }
- int get_h(Node* cur) {
- if (cur == nullptr) return 0;
- return max(get_h(cur->l), get_h(cur->r)) + 1;
- }
- bool bal(Node* cur) {
- return get_h(cur) == 0 || (bal(cur->l) && bal(cur->r) && abs(get_h(cur->l) - get_h(cur->r)) <= 1);
- }
- int main() {
- ifstream fin("input.txt");
- ofstream fout("output.txt");
- int a; fin >> a;
- while (a != 0) {
- add(a, root);
- fin >> a;
- }
- fout << (bal(root) ? "YES" : "NO") << endl;
- fin.close();
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment