Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Balancing Tree to Prevent Skewness #1025

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
Comment on lines +122 to +127
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure firstNode is valid before splaying

There's a potential risk that firstNode might have been modified or removed from the tree before the splay operation when linearCount exceeds the threshold. This could lead to unexpected behavior or runtime errors. Consider adding a check to ensure that firstNode is still a valid node in the tree before performing the splay operation.

Apply this diff to include a validity check:

        } else if t.linearCount > 500 {
+           if t.isValidNode(t.firstNode) {
                t.Splay(t.firstNode)
+           }
            t.linearCount = 0
        }

And implement the isValidNode method:

func (t *Tree[V]) isValidNode(node *Node[V]) bool {
    return node != nil && node.hasLinks()
}

} else {
t.linearCount = 0
}

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