diff options
Diffstat (limited to 'src/02/03/btree.c')
| -rw-r--r-- | src/02/03/btree.c | 44 |
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); } |
