/* 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() { 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; } if (*node) { *node = insert(*node, value); return tree; } *node = new BinaryTree; (*node)->value = value; (*node)->left = (*node)->right = nullptr; (*node)->compare = tree->compare; return tree; } int main(void) { auto tree = new BinaryTree; tree->value = 5; tree->compare = [](int x, int y) { if (x < y) return LT; else if (x > y) return GT; else return EQ; }; for (int i = 0; i <= 5; ++i) { tree = insert(tree, i * 2); } std::cout << tree->left->value << ", " << tree->value << ", " << tree->right->value << std::endl; delete tree; return 0; }