diff options
-rw-r--r-- | impls/btree.cpp | 30 |
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; |