Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cmath>
- #include <tuple>
- #include <set>
- using namespace std;
- class BST {
- struct Node {
- int key;
- int depth;
- Node *l = nullptr, *r = nullptr;
- explicit Node(int key) : key(key) {}
- }
- *root = nullptr;
- bool contains(Node *n, int key) const {
- if (!n) {
- return false;
- } else if (key == n->key) {
- return true;
- } else if (key > n->key) {
- return contains(n->r, key);
- } else {
- return contains(n->l, key);
- }
- }
- void insert(Node *n, int key) {
- if (!root) {
- root = new Node(key);
- return;
- }
- if (key == n->key) {
- return;
- }
- if (key < n->key) {
- if (n->l) {
- insert(n->l, key);
- } else {
- n->l = new Node(key);
- n->l->depth = n->depth + 1;
- }
- } else {
- if (n->r) {
- insert(n->r, key);
- } else {
- n->r = new Node(key);
- n->r->depth = n->depth + 1;
- }
- }
- }
- void MakeDepth(Node *n, int cur_depth) {
- if (n == nullptr) {
- return;
- }
- n->depth = cur_depth;
- MakeDepth(n->l, cur_depth + 1);
- MakeDepth(n->r, cur_depth + 1);
- }
- int depth(Node *n) {
- if (n == nullptr) return 0;
- return max(depth(n->l), depth(n->r)) + 1;
- }
- bool Search(Node *cur_node, int val) {
- if (cur_node == nullptr) {
- return false;
- }
- if (cur_node->key == val) {
- return true;
- }
- if (cur_node->key < val) {
- return Search(cur_node->r, val);
- }
- return Search(cur_node->l, val);
- }
- void order(Node *n) {
- if (n->l) {
- order(n->l);
- }
- for (size_t i = 0; i < n->depth; ++i){
- cout << '.';
- }
- cout << n->key << '\n';
- if (n->r) {
- order(n->r);
- }
- }
- public:
- bool contains(int key) const {
- return contains(root, key);
- }
- void insert(int key) {
- return insert(root, key);
- }
- int depth() {
- return depth(root);
- }
- void MakeDepth(){
- return MakeDepth(root, 1);
- }
- void order() {
- return order(root);
- }
- bool Search(int n) {
- return Search(root, n);
- }
- };
- int main() {
- BST tree;
- string query;
- while (cin >> query) {
- if (query == "ADD") {
- int n;
- cin >> n;
- if (tree.contains(n)) {
- cout << "ALREADY\n";
- } else {
- tree.insert(n);
- cout << "DONE\n";
- }
- } else if (query == "SEARCH") {
- int n;
- cin >> n;
- if (tree.Search(n)) {
- cout << "YES\n";
- } else {
- cout << "NO\n";
- }
- } else {
- tree.order();
- }
- }
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement