diff options
Diffstat (limited to 'src/02/03')
| -rw-r--r-- | src/02/03/btree.c | 44 | ||||
| -rw-r--r-- | src/02/03/main.c | 25 |
2 files changed, 57 insertions, 12 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); } diff --git a/src/02/03/main.c b/src/02/03/main.c index 44e82e2..4f605aa 100644 --- a/src/02/03/main.c +++ b/src/02/03/main.c @@ -1 +1,24 @@ -int main(int argc, char *argv[]) { return 0; } +#include "btree.h" +#include <stdio.h> + +int main(int argc, char *argv[]) { + printf("=== COMP-272 - Assignment 02 - Question 03 ===\n"); + printf("Tree 1: unbalanced tree\n"); + BTree *tree = btree_insert(NULL, 1); + btree_insert(tree, 5); + btree_insert(tree, 2); + btree_insert(tree, 4); + btree_insert(tree, 3); + btree_inspect(tree); + + printf("Tree 2: balanced tree\n"); + tree = btree_insert(NULL, 3); + btree_insert(tree, 2); + btree_insert(tree, 4); + btree_insert(tree, 1); + btree_insert(tree, 5); + btree_inspect(tree); + + printf("Bye\n"); + return 0; +} |
