aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2024-06-23 21:55:16 +0100
committerAryadev Chavali <aryadev@aryadevchavali.com>2024-07-17 20:10:56 +0100
commit262ab3fefa5c2c1ad15a2724d1cc9b87b503ca58 (patch)
tree8579cc262f7d5317494c992999da12a7c6dc2f31
parent894f79581f1717cb1edbef481ba17319f76dee51 (diff)
downloadalgorithms-262ab3fefa5c2c1ad15a2724d1cc9b87b503ca58.tar.gz
algorithms-262ab3fefa5c2c1ad15a2724d1cc9b87b503ca58.tar.bz2
algorithms-262ab3fefa5c2c1ad15a2724d1cc9b87b503ca58.zip
Extracted comparator function into insert caller
-rw-r--r--impls/btree.cpp30
1 files changed, 15 insertions, 15 deletions
diff --git a/impls/btree.cpp b/impls/btree.cpp
index 4067aad..728ae0d 100644
--- a/impls/btree.cpp
+++ b/impls/btree.cpp
@@ -17,13 +17,11 @@ struct BinaryTree
{
T value;
BinaryTree<T> *left, *right;
- enum Order (*compare)(T, T);
- BinaryTree(T val, BinaryTree<T> *l, BinaryTree<T> *r, enum Order (*cmp)(T, T))
+ BinaryTree(T val, BinaryTree<T> *l, BinaryTree<T> *r)
{
value = val;
left = l;
right = r;
- compare = cmp;
}
~BinaryTree()
@@ -34,10 +32,13 @@ struct BinaryTree
};
template <typename T>
-BinaryTree<T> *insert(BinaryTree<T> *tree, T value)
+using comp_fn = enum Order (*)(T, T);
+
+template <typename T>
+BinaryTree<T> *insert(BinaryTree<T> *tree, T value, comp_fn<T> compare)
{
BinaryTree<T> **node = &tree;
- switch (tree->compare(value, tree->value))
+ switch (compare(value, tree->value))
{
case LT:
node = &tree->left;
@@ -47,8 +48,8 @@ BinaryTree<T> *insert(BinaryTree<T> *tree, T value)
node = &tree->right;
break;
}
- *node = *node ? insert(*node, value)
- : new BinaryTree<T>(value, nullptr, nullptr, tree->compare);
+ *node = *node ? insert(*node, value, compare)
+ : new BinaryTree<T>(value, nullptr, nullptr);
return tree;
}
@@ -75,20 +76,18 @@ std::ostream &operator<<(std::ostream &ostream, const BinaryTree<T> *btree)
{
if (!btree)
return ostream;
- ostream << btree->value << "(";
+ ostream << "(" << btree->value;
if (btree->left)
- ostream << btree->left;
- if (btree->left && btree->right)
- ostream << ", ";
+ ostream << " " << btree->left;
if (btree->right)
- ostream << btree->right;
+ ostream << " " << btree->right;
ostream << ")";
return ostream;
}
int main(void)
{
- auto cmp = [](int x, int y)
+ comp_fn<int> cmp = [](int x, int y)
{
if (x < y)
return LT;
@@ -97,10 +96,11 @@ int main(void)
else
return EQ;
};
- auto tree = new BinaryTree<int>(5, NULL, NULL, cmp);
+ auto tree = new BinaryTree<int>(5, NULL, NULL);
for (int i = 0; i <= 5; ++i)
- tree = insert(tree, i * 2);
+ tree = insert(tree, i * 2, cmp);
+ std::cout << tree << std::endl;
leftRotate(&tree);
std::cout << tree << std::endl;