Skip to content

Commit

Permalink
optimize splay tree
Browse files Browse the repository at this point in the history
To prevent the tree from becoming skewed, I balanced it by splaying
the first node of the sequence every 500 linear insert operations.
The value 500 was determined experimentally.
  • Loading branch information
m4ushold committed Oct 2, 2024
1 parent fcf6fbf commit ca47fc7
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions pkg/splay/splay.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,16 @@ func (t *Node[V]) hasLinks() bool {
// Tree is weighted binary search tree which is based on Splay tree.
// original paper on Splay Trees: https://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf
type Tree[V Value] struct {
root *Node[V]
root *Node[V]
linearCount int
firstNode *Node[V]
}

// NewTree creates a new instance of Tree.
func NewTree[V Value](root *Node[V]) *Tree[V] {
return &Tree[V]{
root: root,
root: root,
linearCount: 0,
}
}

Expand All @@ -114,6 +117,18 @@ func (t *Tree[V]) Insert(node *Node[V]) *Node[V] {

// InsertAfter inserts the node after the given previous node.
func (t *Tree[V]) InsertAfter(prev *Node[V], node *Node[V]) *Node[V] {
if prev == t.root {
t.linearCount++
if t.linearCount == 1 {
t.firstNode = node
} else if t.linearCount > 500 {
t.Splay(t.firstNode)
t.linearCount = 0
}
} else {
t.linearCount = 0
}

t.Splay(prev)
t.root = node
node.right = prev.right
Expand Down

0 comments on commit ca47fc7

Please sign in to comment.