This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Top_Tree.cpp
82 lines (81 loc) · 2.13 KB
/
Top_Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <cassert>
class TopTree {
private:
struct Node {
int key;
Node* parent;
Node* left;
Node* right;
Node(int k) : key(k), parent(nullptr), left(nullptr), right(nullptr) {}
};
Node* root;
Node* link(Node* x, int k, Node* y) {
Node* newNode = new Node(k);
newNode->left = x;
newNode->right = y;
if (x != nullptr) x->parent = newNode;
if (y != nullptr) y->parent = newNode;
return newNode;
}
std::pair<Node*, Node*> split(Node* x, int k) {
if (x == nullptr) {
return {nullptr, nullptr};
}
if (x->key <= k) {
auto [left, right] = split(x->right, k);
x->right = left;
if (left != nullptr) left->parent = x;
return {x, right};
} else {
auto [left, right] = split(x->left, k);
x->left = right;
if (right != nullptr) right->parent = x;
return {left, x};
}
}
Node* join(Node* x, Node* y) {
if (x == nullptr) return y;
if (y == nullptr) return x;
while (x->right != nullptr) {
x = x->right;
}
return link(x, y->key, y->left);
}
public:
TopTree() : root(nullptr) {}
void insert(int k) {
auto [left, right] = split(root, k);
root = link(left, k, right);
}
void remove(int k) {
auto [left, right] = split(root, k);
auto [mid, _] = split(right, k + 1);
root = join(left, mid);
}
void inOrderTraversal(Node* x) {
if (x != nullptr) {
inOrderTraversal(x->left);
std::cout << x->key << " ";
inOrderTraversal(x->right);
}
}
void inOrder() {
inOrderTraversal(root);
std::cout << std::endl;
}
};
int main() {
TopTree topTree;
topTree.insert(10);
topTree.insert(5);
topTree.insert(15);
topTree.insert(2);
topTree.insert(7);
std::cout << "Top Tree: ";
topTree.inOrder();
topTree.remove(5);
std::cout << "After removing 5: ";
topTree.inOrder();
return 0;
}