master
1#include "binary_tree.h"
2#include <stdio.h>
3#include <stdlib.h>
4
5/**
6 * Initialize a new node for a Binary Tree.
7 *
8 * @param data the data to assign to the root of the tree.
9 * @return The root of the binary tree.
10 */
11Node *initialize(int data) {
12 Node *item = malloc(sizeof(Node));
13 item->data = data;
14 item->left = NULL;
15 item->right = NULL;
16 return item;
17}
18
19/*
20 * Traverses a binary tree using the traversal algorithm specified.
21 * Time: O(n)
22 * Space: O(n) for each recursive stack frame
23 *
24 * @param node The root of the binary tree
25 * @param vistior A callback function to invoke on each node during the tree
26 * traversal
27 * @param traversal Specifies what type of traversal to perform
28 */
29void traverse(Node *node, Visitor visitor, enum Traversal traversal) {
30 if (!node)
31 return;
32
33 switch (traversal) {
34 case PREORDER:
35 visitor(node);
36 traverse(node->left, visitor, traversal);
37 traverse(node->right, visitor, traversal);
38 break;
39 case INORDER:
40 traverse(node->left, visitor, traversal);
41 visitor(node);
42 traverse(node->right, visitor, traversal);
43 break;
44 case POSTORDER:
45 traverse(node->left, visitor, traversal);
46 traverse(node->right, visitor, traversal);
47 visitor(node);
48 break;
49 default:
50 visitor(node);
51 break;
52 }
53}
54
55/**
56 * Frees the memory allocated for a node in a tree
57 *
58 * @param node The node in the binary tree to free
59 */
60static void destructor(Node *node) { free(node); }
61
62/**
63 * Frees the memory associated with each node in a binary tree.
64 *
65 * @param root The root of the tree
66 */
67void destroy(Node *root) { traverse(root, destructor, POSTORDER); }
68
69/**
70 * A helper method to print out a visual representation of the tree
71 *
72 * @param node A node in a binary tree.
73 * @param level The level in the tree that the node is at
74 */
75void inspect(Node *node, int level) {
76 if (!node)
77 return;
78
79 for (int i = 0; i < level; i++)
80 printf(" ");
81 printf("(%d)\n", node->data);
82 inspect(node->left, level + 1);
83 inspect(node->right, level + 1);
84}