aboutsummaryrefslogtreecommitdiff
path: root/impls/btree.cpp
blob: 4067aada0d507286ab2505e28b62ed1d6416a93f (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* btree.cpp
 * Date: 2021-11-22
 * Author: Aryadev Chavali
 */

#include <iostream>

enum Order
{
  LT,
  GT,
  EQ
};

template <typename T>
struct BinaryTree
{
  T value;
  BinaryTree<T> *left, *right;
  enum Order (*compare)(T, T);
  BinaryTree(T val, BinaryTree<T> *l, BinaryTree<T> *r, enum Order (*cmp)(T, T))
  {
    value   = val;
    left    = l;
    right   = r;
    compare = cmp;
  }

  ~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;
  }
  *node = *node ? insert(*node, value)
                : new BinaryTree<T>(value, nullptr, nullptr, tree->compare);
  return tree;
}

template <typename T>
void rightRotate(BinaryTree<T> **tree)
{
  auto left   = *tree->left;
  *tree->left = left->right;
  left->right = *tree;
  *tree       = left;
}

template <typename T>
void leftRotate(BinaryTree<T> **tree)
{
  auto right     = (*tree)->right;
  (*tree)->right = right->left;
  right->left    = *tree;
  *tree          = right;
}

template <typename T>
std::ostream &operator<<(std::ostream &ostream, const BinaryTree<T> *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<int>(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;
}