Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- #include <algorithm>
- #include <cmath>
- #include <vector>
- #include <string>
- #include <set>
- #include <stack>
- #include <queue>
- #include <deque>
- using namespace std;
- #define TASK "bstsimple"
- struct node {
- int t;
- node *left, *right;
- node(int tt) {
- t = tt;
- left = NULL;
- right = NULL;
- }
- };
- node *root, *last;
- node *find(node *x, int t) {
- if (x == NULL || x->t == t) {
- return x;
- }
- if (t < x->t) {
- return find(x->left, t);
- }
- return find(x->right, t);
- }
- node *min(node *x) {
- if (x->left == NULL) {
- return x;
- }
- return min(x->left);
- }
- node *max(node *x) {
- if (x->right == NULL) {
- return x;
- }
- return max(x->right);
- }
- node *prev(node *x, int t) {
- if (x == NULL || x->t == t) {
- if (x != NULL && x->left != NULL) {
- return max(x->left);
- }
- return last;
- }
- if (t < x->t) {
- return prev(x->left, t);
- }
- last = x;
- return prev(x->right, t);
- }
- node *next(node *x, int t) {
- if (x == NULL || x->t == t) {
- if (x != NULL && x->right != NULL) {
- return min(x->right);
- }
- return last;
- }
- if (t < x->t) {
- last = x;
- return next(x->left, t);
- }
- return next(x->right, t);
- }
- node *ins(node *x, int t) {
- if (x == NULL) {
- return new node(t);
- }
- if (t < x->t) {
- x->left = ins(x->left, t);
- }
- else if (t > x->t) {
- x->right = ins(x->right, t);
- }
- return x;
- }
- node *del(node *x, int t) {
- if (x == NULL) {
- return x;
- }
- if (t < x->t) {
- x->left = del(x->left, t);
- }
- else if (t > x->t) {
- x->right = del(x->right, t);
- }
- else if (x->left != NULL && x->right != NULL) {
- x->t = min(x->right)->t;
- x->right = del(x->right, x->t);
- }
- else if (x->left != NULL) {
- x = x->left;
- }
- else {
- x = x->right;
- }
- return x;
- }
- int main() {
- #ifdef _DEBUG
- freopen("debug.in", "r", stdin);
- freopen("debug.out", "w", stdout);
- #else
- freopen(TASK".in", "r", stdin);
- freopen(TASK".out", "w", stdout);
- #endif // _DEBUG
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- string s;
- int x;
- node *t;
- while (cin >> s) {
- cin >> x;
- switch (s[0]) {
- case 'i': root = ins(root, x); break;
- case 'd': root = del(root, x); break;
- case 'e': cout << (find(root, x) == NULL ? "false\n" : "true\n"); break;
- case 'n': last = NULL; t = next(root, x); if (t == NULL) cout << "none"; else cout << t->t; cout << "\n"; break;
- case 'p': last = NULL; t = prev(root, x); if (t == NULL) cout << "none"; else cout << t->t; cout << "\n"; break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment