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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct _Node {
    int value;
    struct _Node* left;
    struct _Node* right;
} Node;

Node* _create_node(int value) {
    Node* node = malloc(sizeof(*node));
    node->value = value;
    node->left  = NULL;
    node->right = NULL;
    return node;
}

void insert(Node** a_root, int value) {
    // insert(…) for trees is very similar to append(…) for linked lists,
    // except that instead of always adding to the tail, we add to either
    // .left or .right.  Also, we normally use recursion, since we can't
    // keep the address of the tail handy.
    if(*a_root == NULL) {  // If this tree (possibly a subtree) is empty…
        *a_root = _create_node(value);
    }
    else if(value <= (*a_root) -> value) {
        insert(&(*a_root) -> left, value);
    }
    else {
        assert(value > (*a_root) -> value);
        insert(&(*a_root) -> right, value);
    }
}

void destroy(Node** a_root) {
    if(*a_root != NULL) {
        // Destroy left  subtree -- recursive call to destroy(…)
        destroy(& (*a_root) -> left);

        // Destroy right subtree -- recursive call to destroy(…)
        destroy(& (*a_root) -> right);

        // Destroy root ----------- free(…)
        free(*a_root);

        // Set root (in caller's stack frame) to NULL (i.e., empty tree).
        *a_root = NULL;
    }
}

void print_bst(Node* root) {
    if(root != NULL) {
        // Print the left subtree
        print_bst(root -> left);

        // Print the root
        printf("%d\n", root -> value);

        // Print the right subtree
        print_bst(root -> right);
    }
}


int main(int argc, char* argv[]) {
    // Make empty tree
    Node* root = NULL;  // a valid empty tree

    insert(&root, 4);
    insert(&root, 2);
    insert(&root, 4);
    insert(&root, 7);
    insert(&root, 9);
    insert(&root, 0);
    insert(&root, 7);
    insert(&root, 2);
    insert(&root, 3);
    insert(&root, 5);
    insert(&root, 6);
    print_bst(root);
    return EXIT_SUCCESS;
}
/*
    // Assign all fields
    Node temp = {
        .value = value,
        .left  = NULL,
        .right = NULL
    };
    *node = temp; // Yes, you can assign all of the fields in one statement.
*/
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2019 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.