tree

二分探索木

二分探索木
Feb. 2, 2020, 1:51 p.m.

目次

二分探索木とは、すべてのノードが子を最大2つまで持つような木で、かつノードの挿入・検索・削除ができるような木.

木の表現

1
2
3
4
5
6
struct Node {
    int key;
    Node *parent, *left, *right;
}

Node *root, *NIL;

ノードの追加

 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
void insert(int key) {
    Node *x = root;
    Node *y = NIL;
    Node *z = (Node *)malloc(sizeof(Node));

    z->key = key;
    z->left = NIL; z->right = NIL;

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

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

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

走査

先行順序(自身→左→右)での走査.

1
2
3
4
5
6
void preorder(Node *node) {
    if (node == NIL) return;
    cout << " " << node->key;
    preorder(node->left);
    preorder(node->right);
}

検索

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bool find(Node *node, int key) {
    Node* cur = node;
    while (cur != NIL && cur->key != key) {
        if (key < cur->key) {
            cur = cur->left;
        } else {
            cur = cur->right;
        }
    }

    return cur != NIL;
}

削除

 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
void tDelete(Node *z) {
    Node *y, *x;

    if (z->left == NIL || z->right == NIL) y = z;
    else y = tSuccessor(z);

    if (y->left != NIL) {
        x = y->left;
    } else {
        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 {
            y->parent->right = x;
        }
    }

    if (y != z) {
        z->key = y->key;
    }

    free(y);
}