Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #ifndef __AVL_H__
  2. #define __AVL_H__
  3.  
  4.  
  5. #include <functional>
  6. #include <algorithm>
  7. #include <iostream>
  8.  
  9. template <typename T, typename R = T > //
  10. class AVLTree
  11. {
  12. struct Node
  13. {
  14. T e;
  15. Node* l;
  16. Node* r;
  17. int h;
  18.  
  19. Node(T e) : e(e), l(nullptr), r(nullptr), h(0) {}
  20.  
  21. static int height(Node* n) { return n == nullptr ? -1 : n->h; } // if abreviado
  22.  
  23. void updateH() {
  24. h = std::max(Node::height(l), Node::height(r)) + 1;
  25. }
  26.  
  27. };
  28. Node* root;
  29. int length;
  30.  
  31. std::function<R(T)>key;
  32.  
  33. void destroy(Node *n) {
  34. if (n != nullptr)
  35. {
  36. destroy(n->l);
  37. destroy(n->r);
  38. delete n;
  39. }
  40. }
  41.  
  42. void rotAB(Node *& n)
  43. {
  44. Node* aux = n->l;
  45. n->l = aux->r;
  46. n->updateH();
  47. aux->r = n;
  48. n = aux;
  49. n->updateH();
  50. }
  51.  
  52. void rotBA(Node *& n)
  53. {
  54. Node* aux = n->r;
  55. n->r = aux->l;
  56. n->updateH();
  57. aux->l = n;
  58. n = aux;
  59. n->updateH();
  60. }
  61. void balance(Node *& n) {
  62. int delta = Node::height(n->l) - Node::height(n->r);
  63. if( delta < -1){
  64. if (Node::height(n->r->l) > Node::height(n->r->r))
  65. {
  66. rotAB(n->r);
  67. }
  68. rotBA(n);
  69. }else if (delta > 1) {
  70.  
  71. if (Node::height(n->l->r) > Node::height(n->l->l))
  72. {
  73. rotBA(n->l);
  74. }
  75. rotAB(n);
  76. }
  77. }
  78.  
  79. void add(Node*& n, T e) {
  80. if (n == nullptr) {
  81. n = new Node(e);
  82. return;
  83. } else if (key(e) < key(n -> e)) {
  84. add(n->l, e);
  85. } else {
  86. add(n->r, e);
  87. }
  88. balance(n);
  89. n->updateH();
  90. }
  91.  
  92. public:
  93.  
  94. AVLTree(std::function<R(T)>key = [](T a) {return a;}) :root(nullptr), length(0), key(key) {}
  95. ~AVLTree() { destroy(root); }
  96. int Length() { return length; }
  97. int Height() { return Node::height(root); }
  98.  
  99. void Add(T e) {
  100. add(root, e);
  101. ++length;
  102. }
  103.  
  104. };
  105.  
  106.  
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114.  
  115. #endif // __AVL_H__
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement