TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
treap.cpp File Reference

A balanced binary search tree (BST) on the basis of binary search tree and heap: the Treap algorithm implementation. More...

#include <array>
#include <cassert>
#include <cstdint>
#include <iostream>
Include dependency graph for treap.cpp:

Go to the source code of this file.

Classes

struct  data_structures::treap::Treap
 Struct representation of the treap. More...
 

Namespaces

namespace  data_structures
 for IO operations
 
namespace  data_structures::treap
 Functions for the Treap algorithm implementation.
 

Functions

static void test ()
 Self-test implementations.
 
int main ()
 Main function.
 

Variables

const int data_structures::treap::maxNode = 1e5 + 5
 maximum number of nodes
 

Detailed Description

A balanced binary search tree (BST) on the basis of binary search tree and heap: the Treap algorithm implementation.

Implementation of the treap data structre

Support operations including insert, erase, and query (the rank of specified element or the element ranked x) as the same as BST

But these operations take O(log N) time, since treap keeps property of heap using rotate operation, and the desired depth of the tree is O(log N). There's very little chance that it will degenerate into a chain like BST

Author
Kairao ZHENG

Definition in file treap.cpp.

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 255 of file treap.cpp.

255 {
256 test(); // run self-test implementations
257 return 0;
258}
static void test()
Self-test implementations.
Definition treap.cpp:229

◆ test()

static void test ( )
static

Self-test implementations.

Returns
void

< Treap object instance

Definition at line 229 of file treap.cpp.

229 {
231
232 mTreap.insert(1);
233 mTreap.insert(2);
234 mTreap.insert(3);
235 assert(mTreap.get_k_th(2) == 2);
236 mTreap.insert(4);
237 mTreap.insert(5);
238 mTreap.insert(6);
239 assert(mTreap.get_next(4) == 5);
240 mTreap.insert(7);
241 assert(mTreap.get_predecessor(7) == 6);
242 mTreap.erase(4);
243 assert(mTreap.get_k_th(4) == 5);
244 assert(mTreap.get_rank(5) == 4);
245 mTreap.insert(10);
246 assert(mTreap.get_rank(10) == 7);
247 assert(mTreap.get_predecessor(10) == 7);
248
249 std::cout << "All tests have successfully passed!\n";
250}
Struct representation of the treap.
Definition treap.cpp:40
void insert(int k)
Insert element (External method)
Definition treap.cpp:203
int get_next(int k)
Get the successor node of element k.
Definition treap.cpp:188
void erase(int k)
Erase element (External method)
Definition treap.cpp:208
int get_k_th(int k)
Get the KTH largest value (External method)
Definition treap.cpp:214
int get_predecessor(int k)
Get the predecessor node of element k.
Definition treap.cpp:172
int get_rank(int k)
Get the rank of specified element (External method)
Definition treap.cpp:220