From 6d504da381d07115e7bc47b07276ba9105c541c0 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Sun, 25 Jun 2023 07:33:06 +0100 Subject: (*)~reworking this project --- btree.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 7 deletions(-) (limited to 'btree.cpp') diff --git a/btree.cpp b/btree.cpp index 741c8f7..3319aea 100644 --- a/btree.cpp +++ b/btree.cpp @@ -45,13 +45,51 @@ BinaryTree *insert(BinaryTree *tree, T value) *node = insert(*node, value); return tree; } - *node = new BinaryTree; - (*node)->value = value; - (*node)->left = (*node)->right = nullptr; - (*node)->compare = tree->compare; + *node = new BinaryTree; + (*node)->value = value; + (*node)->left = nullptr; + (*node)->right = nullptr; + (*node)->compare = 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; +} + +void test() +{} + int main(void) { auto tree = new BinaryTree; @@ -69,9 +107,9 @@ int main(void) for (int i = 0; i <= 5; ++i) tree = insert(tree, i * 2); - std::cout << tree->left->value << ", " - << tree->value << ", " - << tree->right->value << std::endl; + leftRotate(&tree); + std::cout << tree << std::endl; + delete tree; return 0; } -- cgit v1.2.3-13-gbd6f