ALDS1_8_C

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;

struct Node {
  int key;
  Node *parent, *left, *right;
};

Node *NIL, *root = NIL;


void insert(int k) {
    Node *z,*y = NIL,*r = root;

    z = (Node*)malloc(sizeof(Node));
    z->key = k;
    z->left = NIL;
    z->right = NIL;
    z->parent = NIL;

    if ( r == NIL ) {
        root = z;
        return;
    }

    while ( r != NIL ) {
        y = r;
        if ( k < r->key) r = r->left;
        else r = r->right;
    }

    z->parent = y;
    if ( k < y->key ) y->left = z;
    else y->right = z;
}

Node* find(int k) {
    Node * z = root;
    while ( z != NIL ) {
        if( k == z->key ) break;
        else if ( k < z->key ) z = z->left;
        else z = z->right;
    }

    if ( z == NIL || k != z->key ) return NIL;
    else {
            return z;
    }

    return NIL;
}

void inorder(Node*u) {
    if ( u == NIL ) return;
    inorder(u->left);
    cout << ' ' << u->key;
    inorder(u->right);
}

void preorder(Node *u) {
    if ( u == NIL ) return;
    cout << ' ' << u->key;
    preorder(u->left);
    preorder(u->right);
}

Node * treeSuccessor(Node * x) {
    Node * y = x;
    while ( y != NIL) y = x->left;
    return y;
}

void deleteNode(int k) {
    Node *z = find(k);
    Node *y, *x = NIL;
    if ( z == NIL ) return;
    if ( z->left == NIL || z->right == NIL ) y = z;
    else { y = treeSuccessor(y->right); z->key = y->key;

    if ( y->left != NIL ) x = y->left;
    else if ( y->right != NIL ) x = y->right;

    if ( x != NIL ) x->parent = y->parent;
    if ( y->parent == NIL ) root = x;
    else if ( y == y->parent->left ) y->parent->left = x;
    else if ( y == y->parent->right ) y->parent->right = x;

    free(y);

}

int main(){
    int n,i,temp,b;
    char a[20];
   cin >> n;
    for ( i = 0; i < n; i++ ) {
        cin >> a;
        if ( strcmp(a,"insert") == 0 ) {
             cin >> temp;
            insert(temp);
        }
        else if ( strcmp(a,"print") == 0 ){
            inorder(root);
            cout << endl;
            preorder(root);
            cout << endl;
        }
        else if ( strcmp(a,"find") == 0 ){
            cin >> b;
            if (find(b) != NIL) cout << "yes" << endl;
            else cout << "no" << endl;
        }
        else if ( strcmp(a,"delete") == 0 ) {
            cin >> b;
            deleteNode(b);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值