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

typedef struct _BSTNode {
    int value;
    struct _BSTNode* left;
    struct _BSTNode* right;
} BSTNode;

void insert(int value, BSTNode** a_root) {
    if(*a_root == NULL) {
        *a_root = malloc(sizeof **a_root);
        **a_root = (BSTNode) { .value = value, .left = NULL, .right = NULL };
    }
    else if(value < (*a_root) -> value) {
        insert(value, &((*a_root) -> left));
    }
    else if(value > (*a_root) -> value) {
        insert(value, &((*a_root) -> right));
    }
}

void print_bst_nodes(BSTNode const* root) {
    if(root != NULL) {
        print_bst_nodes(root -> left);
        printf("[%d] ", root -> value);
        print_bst_nodes(root -> right);
    }
}

void print_bst(BSTNode const* root, char const* label) {
    printf("%s%s", label, "");
    print_bst_nodes(root);
    printf("\n");
}

int main(int argc, char* argv[]) {
    BSTNode* root = NULL;
    insert(4, &root);
    insert(2, &root);
    insert(6, &root);
    insert(1, &root);
    insert(3, &root);
    insert(5, &root);
    insert(7, &root);
    print_bst(root, "");
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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