Advertisement
Guest User

Untitled

a guest
Nov 17th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. template<class T, class U, class TCmp, class UCmp>
  2. void Treap<T, U, TCmp, UCmp>::Insert(const T& key, const U& priority) {
  3.   TUNode* cur = dynamic_cast<TUNode*>(root_);
  4.   TUNode* parent_of_cur = nullptr;
  5.  
  6.   // false - left.
  7.   bool last_move = false;
  8.  
  9.   while (cur != nullptr && !cmp_u_(cur->priority, priority)) {
  10.     // If we are less than need.
  11.     parent_of_cur = cur;
  12.     if (cmp_t_(cur->key, key)) {
  13.       cur = dynamic_cast<TUNode*>(cur->right);
  14.       last_move = true;
  15.     } else {
  16.       cur = dynamic_cast<TUNode*>(cur->left);
  17.       last_move = false;
  18.     }
  19.   }
  20.  
  21.   // If the treap is empty
  22.   if (cur == nullptr && parent_of_cur == nullptr) {
  23.     root_ = new TUNode(key, priority);
  24.     return;
  25.   }
  26.  
  27.   // If cur is a leaf, just push.
  28.   if (cur == nullptr) {
  29.     (last_move ? parent_of_cur->right : parent_of_cur->left) =
  30.         new TUNode(key, priority);
  31.     return;
  32.   }
  33.  
  34.   TUNode* left = nullptr;
  35.   TUNode* right = nullptr;
  36.   Split(left, right, cur, key);
  37.  
  38.   TUNode* new_elem = new TUNode(key, priority);
  39.  
  40.   new_elem->left = dynamic_cast<BinNode*>(left);
  41.   new_elem->right = dynamic_cast<BinNode*>(right);
  42.  
  43.   if (parent_of_cur == nullptr) {
  44.     root_ = new TUNode(key, priority);
  45.  
  46.     dynamic_cast<TUNode*>(root_)->left = left;
  47.     dynamic_cast<TUNode*>(root_)->right = right;
  48.  
  49.     return;
  50.   }
  51.  
  52.   (last_move ? parent_of_cur->right : parent_of_cur->left) =
  53.     dynamic_cast<BinNode*>(new_elem);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement