DTL

AVL Tree

Using BST with DTL

Initializing a AVL

#include "avl.hpp"
#include <iostream>

class Obj {
  int value;
public:
  Obj(int value) {
    this->value = value;
  }

  ~Obj() { }

  int getValue() {
    return this->value;
  }
};

int main() {
  // Static
  dby::AVL<int> staAVL;

  // Pointer
  dby::AVL<Obj*, int>* ptrAVL = new dby::AVL<Obj*, int>(
    [](Obj* a){ return a->getValue(); }
  );
  
  delete ptrAVL;
  return 0;
}

Traversing a AVL

#include "avl.hpp"
#include <iostream>

class Obj {
  int value;
public:
  Obj(int value) {
    this->value = value;
  }

  ~Obj() { }

  int getValue() {
    return this->value;
  }
};

int main() {
  // Static
  dby::AVL<int> staAVL;
  staAVL.insert(1);
  staAVL.insert(2);
  staAVL.insert(3);
  staAVL.insert(4);
  staAVL.insert(5);

  std::cout << "DFS TRAVERSALS";
  std::cout << "\nIN ORDER: ";
  staAVL.traverse(dby::avl_traverse::in_order);

  std::cout << "\nPRE ORDER: ";
  staAVL.traverse(dby::avl_traverse::pre_order);

  std::cout << "\nPOST ORDER WITH CUSTOM BEHAVIOR: ";
  staAVL.traverse(dby::avl_traverse::post_order, [](int val){ std::cout << val * val << ' '; });

  // Pointer
  dby::AVL<Obj*, int>* ptrAVL = new dby::AVL<Obj*, int>(
    [](Obj* a){ return a->getValue(); }
  );

  ptrAVL->insert(new Obj(1));
  ptrAVL->insert(new Obj(2));
  ptrAVL->insert(new Obj(3));
  ptrAVL->insert(new Obj(4));
  ptrAVL->insert(new Obj(5));

  std::cout << "\n\nBFS TRAVERSALS";
  std::cout << "\nLEVEL ORDER: ";
  ptrAVL->traverse(dby::avl_traverse::level_order, [](Obj* obj){ std::cout << obj->getValue() << ' '; });

  delete ptrAVL;
  return 0;
}

AVL methods

  • height(): Returns the height of the tree.
  • size(): Returns the length of the tree.
  • find(T value): Returns a pointer to the value if exists in the tree.
  • insert(T value): Adds a new element in the tree.
  • remove(T key): Remove an element from the tree if exists.
  • destroy_tree(): Destroys the tree.
  • search(T key): Find if a key is stored in the tree.