blob: 0ac794fb2d2a3eb3aeedd08c7464803a7d6e2158 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
/* btree.cpp
* Date: 2021-11-22
* Author: Aryadev Chavali
*/
enum Order
{
LT,
GT,
EQ
};
template <typename T>
struct BinaryTree
{
T value;
BinaryTree<T> *left, *right;
enum Order (*compare)(T, T);
~BinaryTree()
{
delete left;
delete right;
}
};
template <typename T>
BinaryTree<T> *insert(BinaryTree<T> *tree, T value)
{
BinaryTree<T> **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<T>;
(*node)->value = value;
(*node)->left = (*node)->right = nullptr;
(*node)->compare = tree->compare;
return tree;
}
|