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>
- #include <map>
- #include <unordered_map>
- 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);
- }
- } else {
- if (n->r) {
- insert(n->r, key);
- } else {
- n->r = new Node(key);
- }
- }
- }
- void MakeDepth(Node *n, int cur_depth){
- if (n == nullptr){
- return;
- }
- n->depth = cur_depth;
- depths[n->key] = n->depth;
- MakeDepth(n->l, cur_depth+1);
- MakeDepth(n->r, cur_depth+1);
- };
- public:
- map<int, int> depths;
- bool contains(int key) const {
- return contains(root, key);
- }
- void insert(int key) {
- return insert(root, key);
- }
- void MakeDepth(){
- return MakeDepth(root, 1);
- }
- };
- int main() {
- int n = -1;
- BST tree;
- vector<int> vec;
- while (n != 0) {
- cin >> n;
- if (n != 0) {
- vec.emplace_back(n);
- tree.insert(n);
- }
- }
- tree.MakeDepth();
- for (auto el: vec){
- cout << tree.depths[el] << " ";
- }
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement