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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct _TreeNode {
int value;
struct _TreeNode* left;
struct _TreeNode* right;
} TreeNode;
// How to insert a node in a BST:
// - If root is empty, then replace root with new node.
// - If value goes in the left, then insert a node in the left subtree (also a BST)
// - If value goes in the right, then insert a node in the right subtree (also a BST)
void insert(int new_value, TreeNode** a_root) {
if(*a_root == NULL) {
*a_root = malloc(sizeof **a_root);
**a_root = (TreeNode) { .value = new_value, .left = NULL, .right = NULL };
}
else if(new_value < (*a_root) -> value) { // don't forget parentheses!
insert(new_value, &(*a_root) -> left);
}
else {
assert(new_value >= (*a_root) -> value); // don't forget parentheses!
insert(new_value, &(*a_root) -> right);
}
}
void print_tree(TreeNode* root) {
// We can only print a non-empty tree.
if(root != NULL) { // IN-ORDER TRAVERSAL (remember this)
print_tree(root -> left); // - Traverse¹ the left subtree
printf("[%d]\n", root -> value); // - Visit² the root
print_tree(root -> right); // - Traverse¹ the right subtree
}
}
void free_bst(TreeNode** a_root) {
if((*a_root) != NULL) {
free_bst(&(*a_root) -> left);
free_bst(&(*a_root) -> right);
free(*a_root);
*a_root = NULL;
}
}
// ¹ "traverse" means do that entire operation the subtree. This is a recursive call.
// ² "visit" means to do an operation to a single node.
int main(int argc, char* argv[]) {
// append(4, &head, &tail) // linked lists
TreeNode* root = NULL; // size == 0 (# of nodes in entire tree)
insert(4, &root); // size == 1
insert(2, &root); // size == 2
insert(6, &root); // size == 3
insert(1, &root); // size == 4
insert(3, &root); // size == 5
insert(5, &root); // size == 6
insert(7, &root); // size == 7
print_tree(root);
free_bst(&root);
assert(root == NULL); // (assertion failed)
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.