Advertisement
vakho

SplayTree v2

Oct 4th, 2015
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template<typename T>
  6. struct Node {
  7.  
  8.     T key;
  9.     Node* child[2];
  10.  
  11.     Node() {
  12.         this->child[0] = nullptr;
  13.         this->child[1] = nullptr;
  14.     }
  15.  
  16.     Node(T key) {
  17.         this->key = key;
  18.         this->child[0] = nullptr;
  19.         this->child[1] = nullptr;
  20.     }
  21.  
  22.     Node(T key, Node* left, Node* right) {
  23.         this->key = key;
  24.         this->child[0] = left;
  25.         this->child[1] = right;
  26.     }
  27. };
  28.  
  29. template <typename T>
  30. Node<T>* tree_rotate(Node<T>* x, bool dir) {
  31.     if (x == nullptr || x->child[dir] == nullptr)
  32.         return x;
  33.     Node<T>* y = x->child[!dir];
  34.     x->child[!dir] = y->child[dir];
  35.     y->child[dir] = x;
  36.     return y;
  37. }
  38.  
  39. template <typename T>
  40. Node<T>* splay_insert(Node<T>* h, T key){
  41.  
  42.     if (nullptr == h) {
  43.         return new Node<T>(key);
  44.     }
  45.  
  46.     if (key < h->key) {
  47.  
  48.         //      Node<T> hl = h.child[0];
  49.         if (nullptr == h->child[0]) {
  50.             return new Node<T>(key, nullptr, h);
  51.         }
  52.  
  53.         if (key < h->child[0]->key) {
  54.             //      Node<T> hll = hl.child[0];
  55.             h->child[0]->child[0] = splay_insert(h->child[0]->child[0], key);
  56.             h = tree_rotate(h, 1);
  57.         }
  58.         else{
  59.             //      Node<T> hlr = hl.child[1];
  60.             h->child[0]->child[1] = splay_insert(h->child[0]->child[1], key);
  61.             h = tree_rotate(h->child[0], 0);
  62.         }
  63.  
  64.         return tree_rotate(h, 1);
  65.     }
  66.  
  67.     //      Node<T> hr = h.child[1];
  68.     if (nullptr == h->child[1]){
  69.         return new Node<T>(key, h, nullptr);
  70.     }
  71.  
  72.     if (key > h->child[1]->key){
  73.         //      Node<T> hrr = hr.child[1];
  74.         h->child[1]->child[1] = splay_insert(h->child[1]->child[1], key);
  75.         h = tree_rotate(h, 0);
  76.     }
  77.     else{
  78.         //      Node<T> hrl = hr.child[0];
  79.         h->child[1]->child[0] = splay_insert(h->child[1]->child[0], key);
  80.         h = tree_rotate(h->child[1], 1);
  81.     }
  82.  
  83.     return tree_rotate(h, 0);
  84. }
  85.  
  86. int main() {
  87.     system("COLOR F0");
  88.  
  89.     Node<int> root(5);
  90.     Node<int> newRoot = *splay_insert(&root, 7);
  91.  
  92.     system("PAUSE");
  93.     return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement