summaryrefslogtreecommitdiff
path: root/src/02/01
diff options
context:
space:
mode:
Diffstat (limited to 'src/02/01')
-rw-r--r--src/02/01/binary_tree.c34
-rw-r--r--src/02/01/binary_tree.h18
2 files changed, 50 insertions, 2 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;
diff --git a/src/02/01/binary_tree.h b/src/02/01/binary_tree.h
index e30b71a..f4ae62c 100644
--- a/src/02/01/binary_tree.h
+++ b/src/02/01/binary_tree.h
@@ -1,3 +1,6 @@
+/**
+ * A struct to represent a node in a Binary Tree
+ */
struct node {
int data;
struct node *left;
@@ -5,8 +8,21 @@ struct node {
};
typedef struct node Node;
+
+/**
+ * A signature of a function pointer
+ * that can be used to traverse a binary tree.
+ */
typedef void(Visitor)(Node* node);
-enum Traversal { INORDER = 1, PREORDER = 2, POSTORDER = 4 };
+
+/**
+ * The different types of traversals that the binary tree can perform
+ */
+enum Traversal {
+ INORDER = 1, // In order traversal
+ PREORDER = 2, // Pre order traversal
+ POSTORDER = 4 // Post order traversal
+};
Node *initialize(int data);
void traverse(Node *node, Visitor visitor, enum Traversal traversal);