diff options
author | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-23 06:19:13 +0000 |
---|---|---|
committer | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-23 06:19:13 +0000 |
commit | 55a24fc5601e05c7dfad9149bc93ac44302f94ae (patch) | |
tree | 0eac2573595828b5b11637fc2968e62c3d7170b8 | |
parent | 8de4860e1d8a1db51e8dbdd12448312613390fc9 (diff) | |
download | algorithms-55a24fc5601e05c7dfad9149bc93ac44302f94ae.tar.gz algorithms-55a24fc5601e05c7dfad9149bc93ac44302f94ae.tar.bz2 algorithms-55a24fc5601e05c7dfad9149bc93ac44302f94ae.zip |
(btree)+recursive insert algorithm
Just checks the value of the current node against value, assesses if
the leaf it needs to store it in is a NULL or not, then either
allocates to that leaf or recursively calls insert on that leaf (so it
may sort the value). Uses pointer magic for some cleaner code.
-rw-r--r-- | btree.cpp | 26 |
1 files changed, 26 insertions, 0 deletions
@@ -24,3 +24,29 @@ struct BinaryTree } }; +template <typename T> +BinaryTree<T> *insert(BinaryTree<T> *tree, T value) +{ + BinaryTree<T> **node = &tree; + switch (tree->compare(value, tree->value)) + { + case LT: + node = &tree->left; + break; + case EQ: + case GT: + node = &tree->right; + break; + } + + if (*node) { + *node = insert(*node, value); + return tree; + } + *node = new BinaryTree<T>; + (*node)->value = value; + (*node)->left = (*node)->right = nullptr; + (*node)->compare = tree->compare; + return tree; +} + |