summaryrefslogtreecommitdiff
path: root/src/02/03/btree.c
diff options
context:
space:
mode:
authormo khan <mo.khan@gmail.com>2020-08-15 18:04:31 -0600
committermo khan <mo.khan@gmail.com>2020-08-15 18:04:31 -0600
commitfddc2c7d930ac8aff78f15f30d832ddeba4e1057 (patch)
treed080bb0baa8530e58d717c2b840a62c7ddc1263c /src/02/03/btree.c
parent3d811c69e67cff7114cbebf3c3971f6470fd6062 (diff)
Document code for the marks
Diffstat (limited to 'src/02/03/btree.c')
-rw-r--r--src/02/03/btree.c44
1 files changed, 33 insertions, 11 deletions
diff --git a/src/02/03/btree.c b/src/02/03/btree.c
index f895c5a..81fcaca 100644
--- a/src/02/03/btree.c
+++ b/src/02/03/btree.c
@@ -1,6 +1,13 @@
#include "btree.h"
#include <stdio.h>
+/**
+ * A helper function used to print a visual
+ * representation of a binary tree.
+ *
+ * @param tree the tree or subtree to inspect
+ * @param level the level of the subtree
+ */
static void inspect(BTree *tree, int level) {
if (!tree)
return;
@@ -13,6 +20,12 @@ static void inspect(BTree *tree, int level) {
inspect(tree->right, level + 1);
}
+/**
+ * Initializes the root of a binary tree
+ *
+ * @param data the data to assign to the root of the tree.
+ * @return Returns the root of the tree.
+ */
BTree *btree_init(int data) {
BTree *tree = malloc(sizeof(BTree));
tree->left = NULL;
@@ -21,25 +34,34 @@ BTree *btree_init(int data) {
return tree;
}
+/**
+ * Inserts a new node into a binary tree.
+ *
+ * @param tree the tree to insert the new new into
+ * @return Returns the root of the tree.
+ */
BTree *btree_insert(BTree *tree, int data) {
if (!tree)
return btree_init(data);
- if (data <= tree->data) {
- if (tree->left) {
+ if (data <= tree->data)
+ if (tree->left)
btree_insert(tree->left, data);
- } else {
+ else
tree->left = btree_init(data);
- }
- } else {
- if (tree->right) {
- btree_insert(tree->right, data);
- } else {
- tree->right = btree_init(data);
- }
- }
+ else if (tree->right)
+ btree_insert(tree->right, data);
+ else
+ tree->right = btree_init(data);
return tree;
}
+/**
+ * A helper function used to print
+ * a visual representation of a binary
+ * tree.
+ *
+ * @param tree The root of the tree to inspect
+ */
void btree_inspect(BTree *tree) { inspect(tree, 0); }