DTL

Binary Search Tree

Using BST with DTL

Initializing a BST

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

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

  ~Obj() { }

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

int main() {
  // Static
  dby::BST<int> staBST;

  // Pointer
  dby::BST<Obj*>* ptrBST = new dby::BST<Obj*>(
    [](Obj* a, Obj* b){ return a->getValue() < b->getValue(); },
    [](Obj* a, Obj* b){ return a->getValue() == b->getValue(); }
  );

  delete ptrBST;
  return 0;
}

Traversing a BST

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

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

  ~Obj() { }

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

int main() {
  // Static
  dby::BST<int> staBST;
  staBST.insert(5);
  staBST.insert(6);
  staBST.insert(4);
  staBST.insert(2);
  staBST.insert(8);

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

  std::cout << "\nPRE ORDER: ";
  staBST.traverse(dby::bst_traverse::pre_order);

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

  // Pointer
  dby::BST<Obj*>* ptrBST = new dby::BST<Obj*>(
    [](Obj* a, Obj* b){ return a->getValue() < b->getValue(); },
    [](Obj* a, Obj* b){ return a->getValue() == b->getValue(); }
  );

  ptrBST->insert(new Obj(5));
  ptrBST->insert(new Obj(6));
  ptrBST->insert(new Obj(4));
  ptrBST->insert(new Obj(2));
  ptrBST->insert(new Obj(8));

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

  delete ptrBST;
  return 0;
}

BST methods

  • height(): Returns the height of the tree.
  • count_nodes(): Returns the total count of nodes in the tree.
  • lowest_element(): Returns a pointer to the lowest element of the tree.
  • highest_element(): Returns a pointer to the highest element 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.
  • count_if(std::function<bool(T)>condition): Returns the number of elements in the tree for which the 'condition' function returns true.
  • search(T key): Find if a key is stored in the tree.