aboutsummaryrefslogtreecommitdiff
path: root/Computer_Science/data_structures/chapter_4/binary_search_tree.c
blob: b498d54d05c4a76ff56ea29fb4440eaa5694a0b4 (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "binary_search_tree.h"
#include "print_ascii_tree.h"

SearchTree make_empty(SearchTree t)
{
    if(t != NULL) {
        make_empty(t->left);
        make_empty(t->right);
        free(t);
    }

    return NULL;
}

/**
 *  find x or return NULL.
 */
Position find(elem_t x, SearchTree t)
{
    if(t != NULL) {
        if(t->elem == x) return t;
        else if(t->elem > x) return find(x, t->right);
        else return find(x, t->left);
    }

    return NULL;
}

Position find_min(SearchTree t)
{
    if(t == NULL)
        return NULL;
    else if(t->left == NULL)
        return t;
    else
        return find_min(t->left);
}

Position find_max(SearchTree t)
{
    if(t == NULL)
        return NULL;
    else if(t->right == NULL)
        return t;
    else
        return find_max(t->right);
}

SearchTree insert(elem_t x, SearchTree t)
{
    if(t == NULL) {
        t = malloc(sizeof(struct TreeNode));
        t->elem = x;
        t->left = NULL;
        t->right = NULL;
    } else if(x > t->elem)
        t->right = insert(x, t->right);
    else if(x < t->elem)
        t->left = insert(x, t->left);
    /* The t->elem = x need do nothing, already inserted */

    return t;
}

SearchTree delete(elem_t x, SearchTree t)
{
    Position p, tmp;

    p = find(x, t);

    if(p == NULL) {
        /* elem x not found */
        printf("x not found!(do nothing)\n");
    } else if(p->left == NULL && p->right == NULL) {
        free(p);
    } else if(p->left == NULL) {
        tmp = p;
        p = p->right;
        free(tmp);
    } else if(p->right == NULL) {
        tmp = p;
        p = p->left;
        free(tmp);
    } else {
        /* replace and delete */
        tmp = find_min(p->right);
        p->elem = tmp->elem;
        t->right = delete(p->elem, t->right);
    }

    return t;
}

elem_t retrieve(Position p)
{

}

void print_tree_pre_order(SearchTree t)
{
    if(t == NULL)
        return;
    print_tree_pre_order(t->left);
    printf("%d ", t->elem);
    print_tree_pre_order(t->right);
}

void test()
{
    SearchTree t = NULL;
    t = make_empty(t);
    t = insert(1, t);
    insert(4, t);
    insert(3, t);
    insert(2, t);
    insert(10, t);
    insert(12, t);
    insert(-1, t);

    print_tree_pre_order(t);
    printf("\n");
    print_ascii_tree(t);
}

int main()
{
    test();
    return 0;
}