-
Notifications
You must be signed in to change notification settings - Fork 0
/
myDSA.h
2930 lines (2719 loc) · 85.5 KB
/
myDSA.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This is the header of myDSA.cpp
* myDSA includes implementations of various data structures and algorithms
* all of the functions are named with a "my-" prefix for distinguishing.
* @author Junkang_Huang [email protected]
**/
# ifndef MYDSA_H
# define MYDSA_H
# include <vector>
# include <list>
# include <string>
# include <queue>
# include <stack>
# include <map>
# include <unordered_map>
# include <ctime>
# include <chrono>
# include <iostream>
# include <fstream>
# include <random>
# include <algorithm>
# include <iomanip>
# include <cmath>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
using std::list;
using std::string;
using std::priority_queue;
//
// -------------------- pTime --------------------
//
//
// A routine to count the time cost by a program in milliseconds.
// Using std::chrono library and std::chrono::steady_clock as clock epoch.
//
// pTime() to create a new counter.
// start(): Start counting.
// addPoint(): Add check points at this moment.
// end(): Stop counting.
// duration(): Return the length of total duration in ms.
// display(): Quickly display the counting result.
//
class pTime{
// alias
using time_point_t = std::chrono::time_point<std::chrono::steady_clock, std::chrono::milliseconds>;
private:
// Member variables
time_point_t startTime; // Start of counting
time_point_t endTime; // End of counting
vector<time_point_t> points; // Checkpoints during counting
bool counting = false; // Whether pTime is still running
public:
// Start couting
void start(){
points.clear();
counting = true;
startTime = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now());
return;
}
// Add check points during counting
void addPoint(){
if ( counting != true ) {
std::cerr << "Invalid check point." << endl;
return;
}
points.push_back(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()));
return;
}
// End counting
void end(){
points.push_back(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()));
counting = false;
endTime = points.back();
return;
}
// Return duration between startTime and end in millisecond.
int duration() const {
if ( counting == true ){
cerr << "pTime is still counting !" << endl;
return 0;
}
return (endTime - startTime).count();
}
// Display counting information
void display() const {
if ( counting == true ){
cerr << "pTime is still counting !" << endl;
return;
}
// Display checkpoints
for (auto i = 0; i < points.size(); ++i)
cout << "# " << i+1 << " " << (points[i]-startTime).count() << " ms" << endl;
// Display total time
cout << endl << "Running time: " << (endTime - startTime).count() << " ms" << endl;
return;
}
// Return a list of checkpoints and end point
vector<int64_t> list() const {
if (counting == true){
cerr << "pTime is still counting !" << endl;
return {};
}
vector<int64_t> list;
for (auto i : points)
list.push_back((i-startTime).count());
return list;
}
};
//
// -------------------- Fundamental --------------------
//
//
// Print:
// Print a container
// con - the container need to print
// os - ostream object where the container to be print to
// mode - "Normal" : print in one line
// "Vertical" : print one item a line
//
template <typename Container>
void myPrint(const Container &con, std::ostream &os = std::cout, string mode = "Normal"){
if ( mode == "Normal" ) {
// "Normal" mode: print in the form as : [ a1, a2, a3, ... ]
os << "[ ";
for (auto itr = con.begin(); itr+1 != con.end(); ++itr)
os << *itr << ", ";
os << con.back() << " ]" << endl;
} else if ( mode == "Vertical" ) {
// "Vertical" mode: print each item at a line
for (auto itr = con.begin(); itr+1 != con.end(); ++itr)
os << *itr << endl;
os << con.back() << endl;
}
return;
}
//
// Swap:
// Swap two elements of a vector
//
template <typename T>
void mySwap (vector<T> &v, int a, int b) {
if ( a == b ) return;
if ( a > v.size() || b > v.size() || a < 0 || b < 0 ) {
cerr << "Error: Invalid index." << endl;
return;
}
std::swap(v[a], v[b]);
return;
}
//
// Histogram:
// A simple histogram plot routine directly on terminal.
// ys should all be non-negtive;
//
template <typename X, typename Y>
void myHist(vector<X> xs, vector<Y> ys, unsigned height = 20, unsigned gap = 8) {
// Test input validaty
if (xs.size() != ys.size()){
cerr << "Error: xs and ys have different size." << endl;
return;
}
for (auto i = 0; i < ys.size(); ++i){
if (ys[i] < 0){
cerr << "y should all be non-negtive." << endl;
return;
}
}
// Find range of y
Y ymax = ys[0];
for (auto i = 0; i < ys.size(); ++i)
ymax = std::max(ymax, ys[i]);
// use a 2-dimention vector to record pixels
vector<vector<bool>> content(height, vector<bool>(xs.size(), 0));
for (auto i = 0; i < xs.size(); ++i){
unsigned parts = static_cast<int>(height*1.0*ys[i]/ymax);
for (auto j = 0; j < parts; ++j)
content[height-1-j][i] = 1;
}
// output
for (auto i = 0; i < height; i++){
for (auto j = 0; j < gap; ++j) cout << " ";
for (auto j = 0; j < xs.size(); ++j){
if (content[i][j]){
cout << "*";
for (auto j = 0; j < gap-1; ++j) cout << " ";
} else{
for (auto j = 0; j < gap; ++j) cout << " ";
}
}
cout << " | " << ymax * (height-i)*1.0 / height << endl;
}
for (auto i = 0; i < xs.size()+1; ++i){
for (auto j = 0; j < gap; ++j) cout << "-";
}
cout << endl << " ";
for (auto i = 0; i < xs.size(); ++i)
cout << std::setw(gap) << xs[i];
cout << endl;
}
//
// -------------------- Linear List --------------------
//
//
// Linked list implementation:
// 1. Just one direction. And for briefness, I do not encapsulate node, and it is visible to users.
// 2. In fact, I could make it more professional if I encapsulate node and create an iterator class for node reference.
// 3. But that would cost heavier works. Maybe in the future!
//
template <typename T>
class myList {
public:
// Internal node structure.
class node {
public:
T getValue() const {
return value;
}
void setValue(T val){
value = val;
}
// Read only, which means that you cannot change the next node through this node.
// The only way that you can change the interconnnection between nodes is through myList functions.
const node *getNext() const {
return next;
}
// Even node is put inside myList,
// if myList want to use the private members, node should still possess a friend claim.
friend class myList<T>;
private:
T value = 0;
node *next = nullptr;
};
// Constructor and destructor
myList () {
head = new node;
tail = new node;
head -> next = tail;
listSize = 0;
}
// Destructor
~myList () {
clear();
delete head;
delete tail;
}
// Attention: Lack of copy function, default only shallow copy
// Get the size
unsigned size() const {
return listSize;
}
// push and pop
void push_back(node *ptr){
insert(tail, ptr);
}
void push_front(node *ptr){
insert(head->next, ptr);
}
void pop_back(){
remove(back());
}
void pop_front(){
remove(head->next);
}
// Insert ptr at the position in front of pos
void insert(node *pos, node *ptr){
node *last = head;
while (last->next != pos){
if (last == tail) {
cerr << "Insert error: inserting position is not in this list." << endl;
return;
}
last = last->next;
}
last->next = ptr;
ptr->next = pos;
++listSize;
}
// Remove node
void remove(node *ptr){
if (empty()){
cerr << "Empty list cannot apply remove()." << endl;
return;
}
node *last = head;
while (last->next != ptr){
if (last == tail){
cerr << "Remove error: node is not in this list." << endl;
return;
}
last = last->next;
}
last->next = ptr->next;
delete ptr;
--listSize;
}
// Front and back, editable
node *back(){
if (empty()){
cerr << "Error: cannot apply back() on empty list." << endl;
return {};
}
node *ptr = head;
while (ptr->next != tail)
ptr = ptr->next;
return ptr;
}
node *front(){
if (empty()){
cerr << "Error: cannot apply front() on empty list." << endl;
return {};
}
return head->next;
}
// Front and back, read only
const node *back() const {
if (empty()){
cerr << "Error: cannot apply back() on empty list." << endl;
return {};
}
node *ptr = head;
while (ptr->next != tail)
ptr = ptr->next;
return ptr;
}
const node *front() const {
if (empty()){
cerr << "Error: cannot apply front() on empty list." << endl;
return {};
}
return head->next;
}
bool empty() const {
return listSize == 0;
}
void clear(){
while (listSize != 0)
pop_front();
}
// Print the list to output
void print(std::ostream &output) const {
auto ptr = head->next;
output << "[";
while (ptr != tail && ptr->next != tail){
output << ptr->value << ", ";
ptr = ptr->next;
}
output << ptr->value << "]" << endl;
}
private:
// Two sentinel nodes at the begin and end of the list
node *head;
node *tail;
unsigned listSize;
};
//
// Stack implementation:
// Use std::vector, and it is pretty easy.
//
template <typename T>
class myStack{
public:
T top() const {
if (empty()){
cerr << "Error: cannot get the top element of empty stack." << endl;
return {};
}
return list.back();
}
void pop() {
if (empty()){
cerr << "Error: cannot apply pop() on empty stack." << endl;
return;
}
list.pop_back();
}
// Left reference input
void push(const T &elem){
list.push_back(elem);
}
// Right reference input
void push(T &&elem){
list.push_back(std::move(elem));
}
bool empty() const {
return list.empty();
}
void clear() {
list.clear();
}
unsigned size() const {
return list.size();
}
private:
vector<T> list;
};
//
// Queue implementation:
// Use circular array
//
template <typename T>
class myQueue{
public:
myQueue():
capacity(16), listSize(0), start(1), end(0){
list = new T[INITSIZE];
}
~myQueue(){
delete list;
}
void push(const T &elem){
if (listSize == capacity - 1)
resize();
// Circular
if (++end == capacity) end = 0;
list[end] = elem;
++listSize;
}
void push(T &&elem){
if (listSize == capacity - 1)
resize();
if (++end == capacity) end = 0;
list[end] = elem;
++listSize;
}
void pop(){
if (empty()){
cerr << "Error: cannot apply pop() on empty queue." << endl;
return;
}
if (++start == capacity) start = 0;
--listSize;
}
// Change the array to new and larger one.
// That is make capacity larger.
void resize() {
T *newList = new T[2*capacity+1];
unsigned j = 0;
for (auto i = start; i != end; ++i){
if (i == capacity) i = 0;
newList[j++] = list[i];
}
newList[j] = list[end];
capacity = capacity*2 + 1;
delete list;
list = newList;
start = 1;
end = 0;
}
T front() const {
return list[start];
}
T back() const {
return list[end];
}
bool empty() const {
return listSize == 0;
}
void clear() {
start = 1;
end = 0;
listSize = 0;
}
unsigned size() const {
return listSize;
}
private:
// Initial capacity of real array
const unsigned INITSIZE = 16;
T *list;
// Capacity is the real capacity of the array
unsigned capacity;
// listSize is the size of valid data
unsigned listSize;
// Start and end mark the start and end position of valid data
unsigned start;
unsigned end;
};
//
// -------------------- Tree --------------------
//
//
// Binary tree node structure
//
template <typename T>
struct myBinaryTreeNode {
T value;
myBinaryTreeNode *left = nullptr;
myBinaryTreeNode *right = nullptr;
// Constructor
myBinaryTreeNode(const T &val): value(val){}
myBinaryTreeNode(T &&val): value(std::move(val)){}
};
//
// Converter from infix to postfix expression
//
std::string infix2Postfix(const string &infix) {
std::vector<char> operatorList{'+','-','*','/','(',')', ' '};
std::map<char, unsigned> priority{
{'(', 100},
{'+', 1}, {'-', 1},
{'*', 2}, {'/', 2}
};
std::stack<char> s;
string postfix;
// Deal with prefix sign '+' and '-'
size_t i = 0;
string infixNew{infix};
while (i < infixNew.size() && infixNew[i] == ' ') ++i;
if (i >= infixNew.size()) return 0;
// Sign at the beginning of expression
if (infixNew[i] == '-' || infixNew[i] == '+')
infixNew.insert(i, 1,'0');
while (i < infixNew.size()-1){
// sign in the middle, '(-' and '(+'
if (infixNew[i] == '(' && (infixNew[i+1] == '-' || infixNew[i+1] == '+'))
infixNew.insert(i+1, 1,'0');
++i;
}
// convert
for (auto c : infixNew){
if ( isdigit(c) || c == '.' ){
postfix.push_back(c);
} else {
postfix.push_back(' ');
if ( c == ' ' ) continue;
if ( c == ')' ){
while ( s.top() != '(' ){
postfix.push_back(s.top());
s.pop();
}
s.pop();
} else {
while ( !s.empty() && s.top() != '(' && priority[s.top()] >= priority[c] ){
postfix.push_back(s.top());
s.pop();
}
s.push(c);
}
}
}
while ( !s.empty() ){
postfix.push_back(s.top());
s.pop();
}
return postfix;
}
//
// Expression Tree Implementation:
// 1. Using myBinaryTreeNode template and use std::string to instantiate it
// 2. In expression tree, leaf node contain operand strings and non-leaf node contain operators (in string).
// 3. Expression public routines include three expression notation: prefix, infix, postfix
// 4. By now, only support binary operators: +, -, *, /
//
class myExpressionTree{
public:
// Destructor
~myExpressionTree(){
clear();
}
// Using std::stack to create expression tree
void readPostfix(const std::string &postfix) {
std::stack<myBinaryTreeNode<string> *> s;
// operand : temperarily store operand strings
std::string operand;
for (auto c : postfix){
if (c == ' ' || c == '+' || c == '-' || c == '*' || c == '/'){
// push operand node to stack
if (!operand.empty()){
myBinaryTreeNode<string> *leaf = new myBinaryTreeNode<string>(operand);
s.push(leaf);
operand.clear();
}
// push operator node to stack
if (c != ' '){
myBinaryTreeNode<string> *node = new myBinaryTreeNode<string>(string() + c);
auto right = s.top(); s.pop();
auto left = s.top(); s.pop();
node->left = left;
node->right = right;
s.push(node);
}
} else {
// record operand string
operand.push_back(c);
}
}
root = s.top(); s.pop();
if (!s.empty()){
cerr << "Error: Invalid postfix expression." << endl;
return;
}
}
// Use infix2Postfix to convert infix to postfix, then read postfix
void readInfix(const std::string &infix) {
std::string postfix = infix2Postfix(infix);
readPostfix(postfix);
}
// Return three types of expression
void printInfix(std::ostream &output = std::cout) const {
printInfix(root, output);
}
void printPostfix(std::ostream &output = std::cout) const {
printPostfix(root, output);
}
void printPrefix(std::ostream &output = std::cout) const {
printPrefix(root, output);
}
// clear() and empty()
void clear() {
clear(root);
}
bool empty() const {
return root == nullptr;
}
private:
// Tree root
myBinaryTreeNode<string> *root = nullptr;
// Private real print function, using pointer as first parameter
void printInfix(myBinaryTreeNode<string> *node, std::ostream &output) const {
if (node == nullptr) return;
printInfix(node->left, output);
output << node->value << " ";
printInfix(node->right, output);
}
void printPostfix(myBinaryTreeNode<string> *node, std::ostream &output) const {
if (node == nullptr) return;
printPostfix(node->left, output);
printPostfix(node->right, output);
output << node->value << " ";
}
void printPrefix(myBinaryTreeNode<string> *node, std::ostream &output) const {
if (node == nullptr) return;
output << node->value << " ";
printPrefix(node->left, output);
printPrefix(node->right, output);
}
// Private real clear function, using pointer as parameter
// Attention: Here use reference of the pointer to node. So the pointer can be set as nullptr.
void clear(myBinaryTreeNode<string> *&node) {
if (node == nullptr) return;
clear(node->left);
clear(node->right);
delete node;
// Set pointer to nullptr
node = nullptr;
}
};
//
// Binary Search Tree (BST):
// node->values repeat is not allowed
//
template <typename T>
class myBST{
public:
// Constructors
myBST() = default;
// Copy constructor
myBST(const myBST<T> &rhs){
root = clone(rhs.root);
}
// Move constructor
myBST(myBST<T> &&rhs){
root = rhs.root;
}
// Destructor
~myBST(){
clear(root);
}
// Get the minimum and maximum value
T min() const {
return min(root);
}
T max() const {
return max(root);
}
// Whether contain val
bool contain(T val) const {
return contain(root, val);
}
// empty and clear
bool empty() const {
return root == nullptr;
}
void clear() {
clear(root);
}
// insert and remove
void insert(const T &val) {
insert(root, val);
}
void insert(T &&val){
insert(root, std::move(val));
}
void remove(const T &val){
remove(root, val);
}
void remove(T &&val){
// Remove a right reference is of no profit
// So I just use left reference again
remove(root, val);
}
private:
// Inner node structure
struct node{
T value;
node *left = nullptr;
node *right = nullptr;
// Constructors
node() = default;
node(const T &val, node *l, node *r):
value(val), left(l), right(r){}
node(T &&val, node *l, node *r):
value(std::move(val)), left(l), right(r){}
};
// The only member variable
node *root = nullptr;
// Return a clone of the tree pointed by ptr
node *clone(node *ptr){
if (ptr == nullptr) return nullptr;
return new node{ptr->value, clone(ptr->left), clone(ptr->right)};
}
// Private versions of all routines
T min(node *ptr) const {
if (ptr == nullptr) {
cerr << "Error: cannot get min value of nullptr" << endl;
return {};
}
T result = ptr->value;
if (ptr->left != nullptr)
result = std::min(result, min(ptr->left));
if (ptr->right != nullptr)
result = std::min(result, min(ptr->right));
return result;
}
T max(node *ptr) const {
if (ptr == nullptr) {
cerr << "Error: cannot get max value of nullptr" << endl;
return {};
}
T result = ptr->value;
if (ptr->left != nullptr)
result = std::max(result, max(ptr->left));
if (ptr->right != nullptr)
result = std::max(result, max(ptr->right));
return result;
}
bool contain(node *ptr, T val) const {
if (ptr == nullptr) return false;
return ptr->value == val || contain(ptr->left, val) || contain(ptr->right, val);
}
void clear(node *&ptr){
if (ptr == nullptr) return;
clear(ptr->left);
clear(ptr->right);
delete ptr;
ptr = nullptr;
}
// Real insert routine
void insert(node *&ptr, const T &val){
if (ptr == nullptr){
auto newNode = new node{val, nullptr, nullptr};
ptr = newNode;
} else if (ptr->value > val){
insert(ptr->left, val);
} else if (ptr->value < val){
insert(ptr->right, val);
} else {
// cerr << "Error: inserted value already exist." << endl;
}
}
void insert(node *&ptr, T &&val){
if (ptr == nullptr){
auto newNode = new node{std::move(val), nullptr, nullptr};
ptr = newNode;
} else if (ptr->value > val){
insert(ptr->left, std::move(val));
} else if (ptr->value < val){
insert(ptr->right, std::move(val));
} else {
// cerr << "Error: inserted value already exist." << endl;
}
}
// Real remove routine
void remove(node *&ptr, const T &val){
if (ptr == nullptr){
// cerr << "Error: removed value dosen't exist." << endl;
return;
}
if (ptr->value > val) remove(ptr->left, val);
else if (ptr->value < val) remove(ptr->right, val);
else {
// For leaf nodes
if (ptr->left == nullptr && ptr->right == nullptr){
delete ptr;
ptr = nullptr;
} else if (ptr->left == nullptr){
// For nodes with only one child at right branch
auto p = ptr;
ptr = ptr->left;
delete p;
} else if (ptr->right == nullptr){
// For nodes with only one child at left branch
auto p = ptr;
ptr = ptr->right;
delete p;
} else {
// For nodes with two children, find the max of right child,
// and move the max value to the node, recursively remove the max node.
auto rightMin = min(ptr->right);
ptr->value = rightMin;
remove(ptr->right, rightMin);
}
}
}
};
//
// AVL Tree:
// Bias is the allowed imbalance of the AVL tree which is set as a private member variable.
//
template <typename T>
class myAVLTree{
public:
myAVLTree() = default;
// You can choose to pass a bias value as b, if you want to change bias. And b should be non-negative.
myAVLTree(const myAVLTree &rhs, int b = 1){
if (b < 0) {
cerr << "Error: bias should be non-negative." << endl;
return;
}
root = clone(rhs.root);
bias = b;
}
myAVLTree(myAVLTree &&rhs, int b = 1){
if (b < 0) {
cerr << "Error: bias should be non-negative." << endl;
return;
}
root = rhs;
bias = b;
}
~myAVLTree(){
clear(root);
}
void clear() {
clear(root);
}
bool empty() const {
return root == nullptr;
}
// Get the height of the tree.
int getHeight() const {
return getHeight(root);
}
// find the maximum and minimum
T max() const {
node *maxNode = max(root);
if (maxNode == nullptr){
cerr << "Error: cannot get the maximum of empty tree." << endl;
return {};
}
return maxNode->value;
}
T min() const {
node *minNode = min(root);
if (minNode == nullptr){
cerr << "Error: cannot get the minimum of empty tree." << endl;
return {};
}
return minNode->value;
}
// public contain, insert and remove, just like them in myBST.
bool contain(const T&val) const {
return contain(val, root);
}
void insert(const T &val) {
insert(val, root);
}
void insert(T &&val){
insert(std::move(val), root);
}
void remove(const T &val){
remove(val, root);
}
void remove(T &&val){
remove(val, root);
}
private:
// inner node structure, there is a height member additional
struct node {
T value;
node *left = nullptr;
node *right = nullptr;
int height = 0;
node(const T &val, node *l, node *r, int h):
value(val), left(l), right(r), height(h) {}
node(T &&val, node *l, node *r, int h):
value(std::move(val)), left(l), right(r), height(h) {}
};
// get the height of the node. For convenience, we set height of nullptr as -1.
int getHeight(node *ptr) const {
return ptr == nullptr ? -1 : ptr->height;
}
// return a clone of the node structure.
node *clone(node *ptr) const {
if (ptr == nullptr) return nullptr;
return new node{ptr->value, clone(ptr->left), clone(ptr->right), ptr->height};
}
void clear(node *&ptr) {
if (ptr == nullptr) return;
clear(ptr->left);
clear(ptr->right);
delete ptr;
ptr = nullptr;
}
node *max(node *ptr) const {
if (ptr == nullptr) return nullptr;
node *maxNode = ptr;
while (maxNode->right != nullptr)
maxNode = maxNode->right;
return maxNode;
}
node *min(node* ptr) const {
if (ptr == nullptr) return nullptr;
node *minNode = ptr;
while (minNode->left != nullptr)
minNode = minNode->left;
return minNode;
}
bool contain(const T &val, node *ptr) const {
if (ptr == nullptr) return false;
if (val < ptr->value) return contain(val, ptr->left);
if (val > ptr->value) return contain(val, ptr->right);
return true;
}
// In AVL tree, insert and remove routines should apply balance() routine to balance the AVL tree.
void insert(const T &val, node *&ptr) {
if (ptr == nullptr) {
node *newNode = new node{val, nullptr, nullptr, 0};
ptr = newNode;
} else if (val < ptr->value){
insert(val, ptr->left);
} else if (val > ptr->value){
insert(val, ptr->right);
} else {