Untitled

mail@pastecode.io avatar
unknown
plain_text
14 days ago
1.7 kB
3
Indexable
Never
struct Node {
    int data;
    Node* left;
    Node* right;

    Node(int value) {
        data = value;
        left = nullptr;
        right = nullptr;
    }
};

class BinaryTree {
private:
    Node* root;

    Node* insert(Node* node, int value) {
        if (node == nullptr) {
            return new Node(value);
        }
        if (value < node->data) {
            node->left = insert(node->left, value);
        } else {
            node->right = insert(node->right, value);
        }
        return node;
    }

    bool isIdeal(Node* node, int level, int& leafLevel) {
        if (node == nullptr) {
            return true;
        }

        if (node->left == nullptr && node->right == nullptr) {
            if (leafLevel == 0) {
                leafLevel = level;
                return true;
            }
            return level == leafLevel;
        }

        if (node->left == nullptr || node->right == nullptr) {
            return false;
        }

        return isIdeal(node->left, level + 1, leafLevel) && isIdeal(node->right, level + 1, leafLevel);
    }

public:
    BinaryTree() {
        root = nullptr;
    }

    void themNut(int value) {
        root = insert(root, value);
    }

    bool kiemTraLyTuong() {
        int leafLevel = 0;
        return isIdeal(root, 0, leafLevel);
    }
};

int main() {
    int n;
    cin >> n;

    BinaryTree cayNhiPhan;

    for (int i = 0; i < n; ++i) {
        int k;
        cin >> k;
        cayNhiPhan.themNut(k);
    }

    if (cayNhiPhan.kiemTraLyTuong()) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }

    return 0;
}
Leave a Comment