/* btree.cpp * Date: 2021-11-22 * Author: Aryadev Chavali */ #include enum Order { LT, GT, EQ }; template struct BinaryTree { T value; BinaryTree *left, *right; BinaryTree(T val, BinaryTree *l, BinaryTree *r) { value = val; left = l; right = r; } ~BinaryTree() { delete left; delete right; } }; template using comp_fn = enum Order (*)(T, T); template BinaryTree *insert(BinaryTree *tree, T value, comp_fn compare) { BinaryTree **node = &tree; switch (compare(value, tree->value)) { case LT: node = &tree->left; break; case EQ: case GT: node = &tree->right; break; } *node = *node ? insert(*node, value, compare) : new BinaryTree(value, nullptr, nullptr); 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->right) ostream << " " << btree->right; ostream << ")"; return ostream; } int main(void) { comp_fn 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); for (int i = 0; i <= 5; ++i) tree = insert(tree, i * 2, cmp); std::cout << tree << std::endl; leftRotate(&tree); std::cout << tree << std::endl; delete tree; return 0; }