From 509c8930e8427ebf0902ba2d886ae638b129e285 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Sun, 9 Jul 2023 16:22:23 +0100 Subject: (btree)+constructor for structure, cleaned up some code Might as well use C++ features if I've got them --- btree.cpp | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) (limited to 'btree.cpp') diff --git a/btree.cpp b/btree.cpp index 3319aea..4067aad 100644 --- a/btree.cpp +++ b/btree.cpp @@ -18,6 +18,14 @@ struct BinaryTree T value; BinaryTree *left, *right; enum Order (*compare)(T, T); + BinaryTree(T val, BinaryTree *l, BinaryTree *r, enum Order (*cmp)(T, T)) + { + value = val; + left = l; + right = r; + compare = cmp; + } + ~BinaryTree() { delete left; @@ -39,17 +47,8 @@ BinaryTree *insert(BinaryTree *tree, T value) node = &tree->right; break; } - - if (*node) - { - *node = insert(*node, value); - return tree; - } - *node = new BinaryTree; - (*node)->value = value; - (*node)->left = nullptr; - (*node)->right = nullptr; - (*node)->compare = tree->compare; + *node = *node ? insert(*node, value) + : new BinaryTree(value, nullptr, nullptr, tree->compare); return tree; } @@ -87,14 +86,9 @@ std::ostream &operator<<(std::ostream &ostream, const BinaryTree *btree) return ostream; } -void test() -{} - int main(void) { - auto tree = new BinaryTree; - tree->value = 5; - tree->compare = [](int x, int y) + auto cmp = [](int x, int y) { if (x < y) return LT; @@ -103,7 +97,7 @@ int main(void) else return EQ; }; - + auto tree = new BinaryTree(5, NULL, NULL, cmp); for (int i = 0; i <= 5; ++i) tree = insert(tree, i * 2); -- cgit v1.2.3-13-gbd6f