Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- using namespace std;
- struct Node {
- Node* right = nullptr;
- Node* left = nullptr;
- Node* prev = nullptr;
- int value;
- Node(int value) : value(value) {}
- };
- struct Tree {
- Node* root = nullptr;
- void addNode(int num, Node* curr) {
- if (num == curr->value)
- return;
- if (curr->value > num) {
- if (curr->left)
- addNode(num, curr->left);
- else {
- curr->left = new Node(num);
- curr->left->prev = curr;
- }
- }
- else {
- if (curr->right)
- addNode(num, curr->right);
- else {
- curr->right = new Node(num);
- curr->right->prev = curr;
- }
- }
- }
- void add(int num) {
- if (!root) {
- root = new Node(num);
- return;
- }
- addNode(num, root);
- }
- Node* find(int n, Node* curr) {
- if (!curr)
- return nullptr;
- if (n == curr->value)
- return curr;
- if (n > curr->value)
- return find(n, curr->right);
- if (n < curr->value)
- return find(n, curr->left);
- return nullptr;
- }
- Node* getRightMost(Node* curr){
- while(curr->right)
- curr = curr->right;
- return curr;
- }
- void remove(int n) {
- Node* node = find(n, root);
- if (!node)
- return;
- if(!node->left && !node->right){
- if(root == node)
- root = nullptr;
- else{
- if(node->prev->left == node)
- node->prev->left = nullptr;
- else
- node->prev->right = nullptr;
- }
- }
- else if(node->left && node->right){
- Node* rightMost = getRightMost(node);
- int rightMostValue = rightMost->value;
- remove(rightMostValue);
- node->value = rightMostValue;
- }
- else{
- Node* child = node->left ? node->left : node->right;
- child->prev = node->prev;
- if(node == root)
- root = child;
- else{
- if(node->prev->left == node)
- node->prev->left = child;
- else
- node->prev->right = child;
- }
- }
- delete node;
- }
- void print_odd_layers(Node* curr, int layer = 1) {
- if (!curr) {
- return;
- }
- if (layer % 2 == 1)
- cout << curr->value << " ";
- print_odd_layers(curr->left, layer + 1);
- print_odd_layers(curr->right, layer + 1);
- }
- void print(Node* curr) {
- if (!curr) {
- return;
- }
- cout << curr->value << " ";
- print(curr->left);
- print(curr->right);
- }
- };
- int main() {
- Tree tree;
- int n;
- string command;
- int a;
- cin >> n;
- for (int i = 0; i < n; i++) {
- cin >> command;
- if (command == "add") {
- cin >> a;
- tree.add(a);
- }
- else if (command == "remove") {
- cin >> a;
- tree.remove(a);
- }
- else if (command == "print") {
- tree.print(tree.root);
- }
- else if (command == "print_odd_layers") {
- tree.print_odd_layers(tree.root);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment