diff options
author | Aryadev Chavali <aryadev@aryadevchavali.com> | 2023-07-09 16:22:23 +0100 |
---|---|---|
committer | Aryadev Chavali <aryadev@aryadevchavali.com> | 2023-07-09 16:22:23 +0100 |
commit | 509c8930e8427ebf0902ba2d886ae638b129e285 (patch) | |
tree | 09df2b23267ba06b92de04dbc9d63170c0c1ee65 | |
parent | 7df5a3c947c2ae9d8ae069a4442ecb8a39c15728 (diff) | |
download | algorithms-509c8930e8427ebf0902ba2d886ae638b129e285.tar.gz algorithms-509c8930e8427ebf0902ba2d886ae638b129e285.tar.bz2 algorithms-509c8930e8427ebf0902ba2d886ae638b129e285.zip |
(btree)+constructor for structure, cleaned up some code
Might as well use C++ features if I've got them
-rw-r--r-- | btree.cpp | 30 |
1 files changed, 12 insertions, 18 deletions
@@ -18,6 +18,14 @@ 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)) + { + value = val; + left = l; + right = r; + compare = cmp; + } + ~BinaryTree() { delete left; @@ -39,17 +47,8 @@ BinaryTree<T> *insert(BinaryTree<T> *tree, T value) node = &tree->right; break; } - - if (*node) - { - *node = insert(*node, value); - return tree; - } - *node = new BinaryTree<T>; - (*node)->value = value; - (*node)->left = nullptr; - (*node)->right = nullptr; - (*node)->compare = tree->compare; + *node = *node ? insert(*node, value) + : new BinaryTree<T>(value, nullptr, nullptr, tree->compare); return tree; } @@ -87,14 +86,9 @@ std::ostream &operator<<(std::ostream &ostream, const BinaryTree<T> *btree) return ostream; } -void test() -{} - int main(void) { - auto tree = new BinaryTree<int>; - 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<int>(5, NULL, NULL, cmp); for (int i = 0; i <= 5; ++i) tree = insert(tree, i * 2); |