Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- using namespace std;
- struct node {
- node *l, *r;
- int key;
- node(int k) {
- this->key = k;
- }
- };
- struct binary_tree {
- private:
- node *root = nullptr;
- node * search(node * cur, int k) {
- if (cur == NULL) {
- return NULL;
- }
- if (k == cur->key) {
- return cur;
- }
- if (k < cur->key) {
- return search(cur->l, k);
- } else {
- return search(cur->r, k);
- }
- }
- node * add(node *cur, int key) {
- if (cur == NULL) {
- return new node(key);
- }
- if (key < cur->key) {
- cur->l = add(cur->l, key);
- } else {
- cur->r = add(cur->r, key);
- }
- return cur;
- }
- void print(node *cur) {
- if (cur != nullptr) {
- print(cur->l);
- cout << cur->key << " ";
- print(cur->r);
- }
- }
- int depth(node * cur, int key) {
- if (cur->key == key) return 1;
- else if (key > cur->key) return 1 + depth(cur->r, key);
- return 1 + depth(cur->l, key);
- }
- node *minimum(node *cur) {
- if (cur->l == nullptr) {
- return cur;
- }
- return minimum(cur->l);
- }
- //*(cur).l == cur->l
- node * erase(node *cur, int key) {
- if (cur == nullptr) {
- return cur;
- }
- if (key < cur->key) {
- cur->l = erase(cur->l, key);
- } else if (key > cur->key) {
- cur->r = erase(cur->r, key);
- } else if (cur->l != nullptr && cur->r != nullptr) {
- cur->key = minimum(cur->r)->key;
- cur->r = erase(root->r, cur->key);
- } else {
- if (cur->l != nullptr) {
- cur = cur->l;
- } else if (cur->r != nullptr) {
- cur = cur->r;
- } else {
- cur = nullptr;
- }
- }
- };
- public:
- bool search(int key) {
- if (search(root, key) == nullptr) {
- return 0;
- }
- return 1;
- }
- void add(int key) {
- if (!search(key)) {
- root = add(root, key);
- }
- }
- void print() {
- print(root);
- }
- void erase(int key) {
- erase(root, key);
- }
- int depth (int x) {
- return depth(root, x);
- }
- };
- int main() {
- binary_tree a;
- int x;
- cin >> x;
- while (x!=0) {
- if (!a.search(x)) {
- a.add(x);
- cout << a.depth(x);
- }
- cin >> x;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement