Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <string>
- #include <utility>
- #include <iostream>
- #include <algorithm>
- struct Node {
- char color;
- int key;
- struct Node *left;
- struct Node *right;
- struct Node *parent;
- };
- std::pair<bool, int> chk(Node *n) {
- if (n == nullptr) {
- return {true, 1};
- }
- if ((n->left && (n->left->key >= n->key)) || (n->right && (n->right->key <= n->key))) {
- return {false, -1};
- }
- int cnt;
- if (n->color == 'R') {
- cnt = 0;
- if ((n->left && n->left->color == 'R') || (n->right && n->right->color == 'R')) {
- return {false, -1};
- }
- } else {
- cnt = 1;
- }
- std::pair<bool, int> pr = chk(n->right);
- std::pair<bool, int> pl = chk(n->left);
- return {pr.first && pl.first && (pr.second == pl.second), pr.second + cnt};
- }
- bool isBalanced(Node *n) {
- if (n->color == 'R') {
- return false;
- }
- return chk(n).first;
- }
- int main() {
- int n = 0, root_num = 0;
- std::cin >> n;
- if (n == 0) {
- std::cout << "NO\n";
- exit(0);
- }
- std::cin >> root_num;
- auto nodes = new Node *[n + 1];
- for (int i = 1; i < n + 1; ++i) {
- nodes[i] = new Node;
- }
- int number;
- std::string left, right;
- for (int i = 1; i <= n; ++i) {
- std::cin >> number >> nodes[number]->key >> left >> right >> nodes[number]->color;
- if (left != "null") {
- nodes[number]->left = nodes[std::stoi(left)];
- nodes[std::stoi(left)]->parent = nodes[number];
- } else {
- nodes[number]->left = nullptr;
- }
- if (right != "null") {
- nodes[number]->right = nodes[std::stoi(right)];
- nodes[std::stoi(right)]->parent = nodes[number];
- } else {
- nodes[number]->right = nullptr;
- }
- }
- if (isBalanced(nodes[root_num])) {
- std::cout << "YES\n";
- } else {
- std::cout << "NO\n";
- }
- for (int i = 1; i < n + 1; ++i) {
- delete nodes[i];
- }
- delete[] nodes;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement