This repository has been archived by the owner on Apr 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced_tree.h
121 lines (98 loc) · 2.17 KB
/
balanced_tree.h
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
110
111
112
113
114
115
116
117
118
119
120
121
//
// Created by Limpol on 2022/10/10.
//
#pragma once
#include <memory>
template<typename T>
class TreeNode
{
public:
T element;
using ptr = std::unique_ptr<TreeNode<T>>;
ptr left = nullptr;
ptr right = nullptr;
inline int height() const
{
int leftHeight = left ? left->height() : 0;
int rightHeight = right ? right->height() : 0;
return 1 + std::max(leftHeight, rightHeight);
}
TreeNode() = default;
explicit TreeNode(T data) : element(data), left(nullptr), right(nullptr)
{}
private:
TreeNode(T data, ptr left, ptr right) :
element(data), left(left), right(right)
{}
};
template<typename T>
class AVL_Tree
{
public:
using ptr = std::unique_ptr<TreeNode<T>>;
AVL_Tree() : root(nullptr)
{}
explicit AVL_Tree(T data) : root(new TreeNode<T>(data))
{}
AVL_Tree(T data, AVL_Tree<T> &left, AVL_Tree<T> &right) :
root(new TreeNode<T>(data, left.root, right.root, nullptr))
{
left.root = nullptr;
right.root = nullptr;
}
~AVL_Tree() = default;
ptr search(const T &);
void insert(T data)
{
insert(data, root);
}
void remove(T data)
{
remove(data, root);
}
bool empty()
{ return root == nullptr; }
void clear()
{ destroy(root); }
void print()
{ print(root); }
private:
ptr root;
ptr RR_rotate(ptr &);
ptr LL_rotate(ptr &);
ptr LR_rotate(ptr &);
ptr RL_rotate(ptr &);
};
template<typename T>
std::unique_ptr<TreeNode<T>> AVL_Tree<T>::search(const T &x)
{
auto t = root;
auto p(t);
while (t != nullptr)
{
p = t;
if (t->element == x)
return t;
else if (t->element > x)
t = t->left;
else
t = t->right;
}
return p;
}
template<typename T>
typename AVL_Tree<T>::ptr AVL_Tree<T>::RR_rotate(AVL_Tree::ptr &k1)//left rotate
{
auto k2 = k1->right;
k1->right= k2->left;
k2->left = k1;
return k2;
}
template<typename T>
typename AVL_Tree<T>::ptr AVL_Tree<T>::LL_rotate(AVL_Tree::ptr &k2)
{
auto k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
return k1;
}