summaryrefslogtreecommitdiff
path: root/src/02/01/binary_tree.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/02/01/binary_tree.c')
-rw-r--r--src/02/01/binary_tree.c34
1 files changed, 33 insertions, 1 deletions
diff --git a/src/02/01/binary_tree.c b/src/02/01/binary_tree.c
index cc3e666..16eec3d 100644
--- a/src/02/01/binary_tree.c
+++ b/src/02/01/binary_tree.c
@@ -2,6 +2,12 @@
#include <stdio.h>
#include <stdlib.h>
+/**
+ * Initialize a new node for a Binary Tree.
+ *
+ * @param data the data to assign to the root of the tree.
+ * @return The root of the binary tree.
+ */
Node *initialize(int data) {
Node *item = malloc(sizeof(Node));
item->data = data;
@@ -10,6 +16,16 @@ Node *initialize(int data) {
return item;
}
+/*
+ * Traverses a binary tree using the traversal algorithm specified.
+ * Time: O(n)
+ * Space: O(1)
+ *
+ * @param node The root of the binary tree
+ * @param vistior A callback function to invoke on each node during the tree
+ * traversal
+ * @param traversal Specifies what type of traversal to perform
+ */
void traverse(Node *node, Visitor visitor, enum Traversal traversal) {
if (!node)
return;
@@ -36,10 +52,26 @@ void traverse(Node *node, Visitor visitor, enum Traversal traversal) {
}
}
+/**
+ * Frees the memory allocated for a node in a tree
+ *
+ * @param node The node in the binary tree to free
+ */
static void destructor(Node *node) { free(node); }
-void destroy(Node *head) { traverse(head, destructor, POSTORDER); }
+/**
+ * Frees the memory associated with each node in a binary tree.
+ *
+ * @param root The root of the tree
+ */
+void destroy(Node *root) { traverse(root, destructor, POSTORDER); }
+/**
+ * A helper method to print out a visual representation of the tree
+ *
+ * @param node A node in a binary tree.
+ * @param level The level in the tree that the node is at
+ */
void inspect(Node *node, int level) {
if (!node)
return;