How to create and use SplayTree in Julia
Overview
SplayTree is a self-balancing binary search tree. It has an additional property with the recently accessed elements to quickly access it.
The time complexity for the insert, search, and delete is .
Note: is the number of nodes in the
SplayTree.
Example
Below is a sample code for using a SplayTree in Julia:
using DataStructures# create a new spaly treesplayTree = SplayTree();push!(splayTree, 1)push!(splayTree, 5)push!(splayTree, 2)push!(splayTree, 4)push!(splayTree, 10)for k in 1:length(splayTree)println("tree[$(k)] :", splayTree[k] )end#check if the spalytree contains a keyprintln("Check if spalytree has key 4 :", haskey(splayTree, 4))# deleting 4 from the splayTreedelete!(splayTree, 4)println("After deleting 4, The spalyTree is")# print the elements of splayTreefor k in 1:length(splayTree)println("tree[$(k)] :", splayTree[k] )end
Explanation
- Line 4: We create a
SplayTreeobject with the namesplayTree. - Lines 6–10: We use the
push!method to insert five elements into thesplayTree. - Line 12–14: We print the elements of the
splayTree. - Line 18: We use the
haskeymethod to check if thesplayTreecontains key4. - Line 21: We use the
deletemethod to delete the key4from thesplayTree.
Note: The complete reference to the
SplayTreecan be found on the official Julia page here.