From 4359caa3ca15c75c4241d869259af3be8cc8375f Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Mon, 29 Apr 2024 15:43:17 +0530 Subject: Moved implementations to folder --- impls/btree.cpp | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 impls/btree.cpp (limited to 'impls/btree.cpp') diff --git a/impls/btree.cpp b/impls/btree.cpp new file mode 100644 index 0000000..4067aad --- /dev/null +++ b/impls/btree.cpp @@ -0,0 +1,109 @@ +/* btree.cpp + * Date: 2021-11-22 + * Author: Aryadev Chavali + */ + +#include + +enum Order +{ + LT, + GT, + EQ +}; + +template +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; + delete right; + } +}; + +template +BinaryTree *insert(BinaryTree *tree, T value) +{ + BinaryTree **node = &tree; + switch (tree->compare(value, tree->value)) + { + case LT: + node = &tree->left; + break; + case EQ: + case GT: + node = &tree->right; + break; + } + *node = *node ? insert(*node, value) + : new BinaryTree(value, nullptr, nullptr, tree->compare); + return tree; +} + +template +void rightRotate(BinaryTree **tree) +{ + auto left = *tree->left; + *tree->left = left->right; + left->right = *tree; + *tree = left; +} + +template +void leftRotate(BinaryTree **tree) +{ + auto right = (*tree)->right; + (*tree)->right = right->left; + right->left = *tree; + *tree = right; +} + +template +std::ostream &operator<<(std::ostream &ostream, const BinaryTree *btree) +{ + if (!btree) + return ostream; + ostream << btree->value << "("; + if (btree->left) + ostream << btree->left; + if (btree->left && btree->right) + ostream << ", "; + if (btree->right) + ostream << btree->right; + ostream << ")"; + return ostream; +} + +int main(void) +{ + auto cmp = [](int x, int y) + { + if (x < y) + return LT; + else if (x > y) + return GT; + else + return EQ; + }; + auto tree = new BinaryTree(5, NULL, NULL, cmp); + for (int i = 0; i <= 5; ++i) + tree = insert(tree, i * 2); + + leftRotate(&tree); + std::cout << tree << std::endl; + + delete tree; + return 0; +} -- cgit v1.2.3-13-gbd6f