Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Playground

doc.gno

// v0 - Unaudited: This is an initial version that has not yet been formally audited.
// A fully audited version will be published as a subsequent release.
// Use in production at your own risk.
//
// Package avl provides a gas-efficient AVL tree implementation for storing
// key-value data in Gno realms.
package avl

gnomod.toml

module = "gno.land/p/nt/avl/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

node.gno

package avl

//----------------------------------------
// Node

// Node represents a node in an AVL tree.
type Node struct {
	key       string // key is the unique identifier for the node.
	value     any    // value is the data stored in the node.
	height    int8   // height is the height of the node in the tree.
	size      int    // size is the number of leaf nodes (key-value pairs) in the subtree rooted at this node.
	leftNode  *Node  // leftNode is the left child of the node.
	rightNode *Node  // rightNode is the right child of the node.
}

// NewNode creates a new node with the given key and value.
func NewNode(key string, value any) *Node {
	return &Node{
		key:    key,
		value:  value,
		height: 0,
		size:   1,
	}
}

// Size returns the size of the subtree rooted at the node.
func (node *Node) Size() int {
	if node == nil {
		return 0
	}
	return node.size
}

// IsLeaf checks if the node is a leaf node (has no children).
func (node *Node) IsLeaf() bool {
	return node.height == 0
}

// Key returns the key of the node.
func (node *Node) Key() string {
	return node.key
}

// Value returns the value of the node.
func (node *Node) Value() any {
	return node.value
}

func (node *Node) _copy() *Node {
	if node.height == 0 {
		panic("Why are you copying a value node?")
	}
	return &Node{
		key:       node.key,
		height:    node.height,
		size:      node.size,
		leftNode:  node.leftNode,
		rightNode: node.rightNode,
	}
}

// Has checks if a node with the given key exists in the subtree rooted at the node.
func (node *Node) Has(key string) (has bool) {
	if node == nil {
		return false
	}
	if node.key == key {
		return true
	}
	if node.height == 0 {
		return false
	} else {
		if key < node.key {
			return node.getLeftNode().Has(key)
		} else {
			return node.getRightNode().Has(key)
		}
	}
}

// Get searches for a node with the given key in the subtree rooted at the node
// and returns its index, value, and whether it exists.
func (node *Node) Get(key string) (index int, value any, exists bool) {
	if node == nil {
		return 0, nil, false
	}

	if node.height == 0 {
		if node.key == key {
			return 0, node.value, true
		} else if node.key < key {
			return 1, nil, false
		} else {
			return 0, nil, false
		}
	} else {
		if key < node.key {
			return node.getLeftNode().Get(key)
		} else {
			rightNode := node.getRightNode()
			index, value, exists = rightNode.Get(key)
			index += node.size - rightNode.size
			return index, value, exists
		}
	}
}

// GetByIndex retrieves the key-value pair of the node at the given index
// in the subtree rooted at the node.
func (node *Node) GetByIndex(index int) (key string, value any) {
	if index < 0 {
		panic("GetByIndex: negative index not allowed")
	}

	if node.height == 0 {
		if index != 0 {
			panic("GetByIndex asked for invalid index")
		}
		return node.key, node.value
	} else {
		// TODO: could improve this by storing the sizes
		leftNode := node.getLeftNode()
		if index < leftNode.size {
			return leftNode.GetByIndex(index)
		} else {
			return node.getRightNode().GetByIndex(index - leftNode.size)
		}
	}
}

// Set inserts a new node with the given key-value pair into the subtree rooted at the node,
// and returns the new root of the subtree and whether an existing node was updated.
//
// XXX consider a better way to do this... perhaps split Node from Node.
func (node *Node) Set(key string, value any) (newSelf *Node, updated bool) {
	if node == nil {
		return NewNode(key, value), false
	}
	if node.height == 0 {
		if key < node.key {
			return &Node{
				key:       node.key,
				height:    1,
				size:      2,
				leftNode:  NewNode(key, value),
				rightNode: node,
			}, false
		} else if key == node.key {
			return NewNode(key, value), true
		} else {
			return &Node{
				key:       key,
				height:    1,
				size:      2,
				leftNode:  node,
				rightNode: NewNode(key, value),
			}, false
		}
	} else {
		node = node._copy()
		if key < node.key {
			node.leftNode, updated = node.getLeftNode().Set(key, value)
		} else {
			node.rightNode, updated = node.getRightNode().Set(key, value)
		}
		if updated {
			return node, updated
		} else {
			node.calcHeightAndSize()
			return node.balance(), updated
		}
	}
}

// Remove deletes the node with the given key from the subtree rooted at the node.
// returns the new root of the subtree, the new leftmost leaf key (if changed),
// the removed value and the removal was successful.
func (node *Node) Remove(key string) (
	newNode *Node, newKey string, value any, removed bool,
) {
	if node == nil {
		return nil, "", nil, false
	}
	if node.height == 0 {
		if key == node.key {
			return nil, "", node.value, true
		} else {
			return node, "", nil, false
		}
	} else {
		if key < node.key {
			var newLeftNode *Node
			newLeftNode, newKey, value, removed = node.getLeftNode().Remove(key)
			if !removed {
				return node, "", value, false
			} else if newLeftNode == nil { // left node held value, was removed
				return node.rightNode, node.key, value, true
			}
			node = node._copy()
			node.leftNode = newLeftNode
			node.calcHeightAndSize()
			node = node.balance()
			return node, newKey, value, true
		} else {
			var newRightNode *Node
			newRightNode, newKey, value, removed = node.getRightNode().Remove(key)
			if !removed {
				return node, "", value, false
			} else if newRightNode == nil { // right node held value, was removed
				return node.leftNode, "", value, true
			}
			node = node._copy()
			node.rightNode = newRightNode
			if newKey != "" {
				node.key = newKey
			}
			node.calcHeightAndSize()
			node = node.balance()
			return node, "", value, true
		}
	}
}

func (node *Node) getLeftNode() *Node {
	return node.leftNode
}

func (node *Node) getRightNode() *Node {
	return node.rightNode
}

// rotateRight performs a right rotation on the node and returns the new root.
// NOTE: overwrites node
// TODO: optimize balance & rotate
func (node *Node) rotateRight() *Node {
	node = node._copy()
	l := node.getLeftNode()
	_l := l._copy()

	_lrCached := _l.rightNode
	_l.rightNode = node
	node.leftNode = _lrCached

	node.calcHeightAndSize()
	_l.calcHeightAndSize()

	return _l
}

// rotateLeft performs a left rotation on the node and returns the new root.
// NOTE: overwrites node
// TODO: optimize balance & rotate
func (node *Node) rotateLeft() *Node {
	node = node._copy()
	r := node.getRightNode()
	_r := r._copy()

	_rlCached := _r.leftNode
	_r.leftNode = node
	node.rightNode = _rlCached

	node.calcHeightAndSize()
	_r.calcHeightAndSize()

	return _r
}

// calcHeightAndSize updates the height and size of the node based on its children.
// NOTE: mutates height and size
func (node *Node) calcHeightAndSize() {
	node.height = maxInt8(node.getLeftNode().height, node.getRightNode().height) + 1
	node.size = node.getLeftNode().size + node.getRightNode().size
}

// calcBalance calculates the balance factor of the node.
func (node *Node) calcBalance() int {
	return int(node.getLeftNode().height) - int(node.getRightNode().height)
}

// balance balances the subtree rooted at the node and returns the new root.
// NOTE: assumes that node can be modified
// TODO: optimize balance & rotate
func (node *Node) balance() (newSelf *Node) {
	balance := node.calcBalance()
	if balance > 1 {
		if node.getLeftNode().calcBalance() >= 0 {
			// Left Left Case
			return node.rotateRight()
		} else {
			// Left Right Case
			left := node.getLeftNode()
			node.leftNode = left.rotateLeft()
			return node.rotateRight()
		}
	}
	if balance < -1 {
		if node.getRightNode().calcBalance() <= 0 {
			// Right Right Case
			return node.rotateLeft()
		} else {
			// Right Left Case
			right := node.getRightNode()
			node.rightNode = right.rotateRight()
			return node.rotateLeft()
		}
	}
	// Nothing changed
	return node
}

// Shortcut for TraverseInRange.
func (node *Node) Iterate(start, end string, cb func(*Node) bool) bool {
	return node.TraverseInRange(start, end, true, true, cb)
}

// Shortcut for TraverseInRange.
func (node *Node) ReverseIterate(start, end string, cb func(*Node) bool) bool {
	return node.TraverseInRange(start, end, false, true, cb)
}

// TraverseInRange traverses all nodes, including inner nodes.
// Start is inclusive and end is exclusive when ascending,
// Start and end are inclusive when descending.
// Empty start and empty end denote no start and no end.
// If leavesOnly is true, only visit leaf nodes.
// NOTE: To simulate an exclusive reverse traversal,
// just append 0x00 to start.
func (node *Node) TraverseInRange(start, end string, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {
	if node == nil {
		return false
	}
	afterStart := (start == "" || start < node.key)
	startOrAfter := (start == "" || start <= node.key)
	beforeEnd := false
	if ascending {
		beforeEnd = (end == "" || node.key < end)
	} else {
		beforeEnd = (end == "" || node.key <= end)
	}

	// Run callback per inner/leaf node.
	stop := false
	if (!node.IsLeaf() && !leavesOnly) ||
		(node.IsLeaf() && startOrAfter && beforeEnd) {
		stop = cb(node)
		if stop {
			return stop
		}
	}
	if node.IsLeaf() {
		return stop
	}

	if ascending {
		// check lower nodes, then higher
		if afterStart {
			stop = node.getLeftNode().TraverseInRange(start, end, ascending, leavesOnly, cb)
		}
		if stop {
			return stop
		}
		if beforeEnd {
			stop = node.getRightNode().TraverseInRange(start, end, ascending, leavesOnly, cb)
		}
	} else {
		// check the higher nodes first
		if beforeEnd {
			stop = node.getRightNode().TraverseInRange(start, end, ascending, leavesOnly, cb)
		}
		if stop {
			return stop
		}
		if afterStart {
			stop = node.getLeftNode().TraverseInRange(start, end, ascending, leavesOnly, cb)
		}
	}

	return stop
}

// TraverseByOffset traverses all nodes, including inner nodes.
// A limit of math.MaxInt means no limit.
func (node *Node) TraverseByOffset(offset, limit int, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {
	if node == nil {
		return false
	}

	// Clamp negative offset to 0; otherwise `delta := first.size - offset`
	// over-counts and silently drops nodes.
	if offset < 0 {
		offset = 0
	}

	// fast paths. these happen only if TraverseByOffset is called directly on a leaf.
	if limit <= 0 || offset >= node.size {
		return false
	}
	if node.IsLeaf() {
		if offset > 0 {
			return false
		}
		return cb(node)
	}

	// go to the actual recursive function.
	return node.traverseByOffset(offset, limit, ascending, leavesOnly, cb)
}

// TraverseByOffset traverses the subtree rooted at the node by offset and limit,
// in either ascending or descending order, and applies the callback function to each traversed node.
// If leavesOnly is true, only leaf nodes are visited.
func (node *Node) traverseByOffset(offset, limit int, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {
	// caller guarantees: offset < node.size; limit > 0.
	if !leavesOnly {
		if cb(node) {
			return true // Stop traversal if callback returns true
		}
	}
	first, second := node.getLeftNode(), node.getRightNode()
	if !ascending {
		first, second = second, first
	}
	if first.IsLeaf() {
		// either run or skip, based on offset
		if offset > 0 {
			offset--
		} else {
			if cb(first) {
				return true // Stop traversal if callback returns true
			}
			limit--
			if limit <= 0 {
				return true // Stop traversal when limit is reached
			}
		}
	} else {
		// possible cases:
		// 1 the offset given skips the first node entirely
		// 2 the offset skips none or part of the first node, but the limit requires some of the second node.
		// 3 the offset skips none or part of the first node, and the limit stops our search on the first node.
		if offset >= first.size {
			offset -= first.size // 1
		} else {
			if first.traverseByOffset(offset, limit, ascending, leavesOnly, cb) {
				return true
			}
			// number of leaves which could actually be called from inside
			delta := first.size - offset
			offset = 0
			if delta >= limit {
				return true // 3
			}
			limit -= delta // 2
		}
	}

	// because of the caller guarantees and the way we handle the first node,
	// at this point we know that limit > 0 and there must be some values in
	// this second node that we include.

	// => if the second node is a leaf, it has to be included.
	if second.IsLeaf() {
		return cb(second)
	}
	// => if it is not a leaf, it will still be enough to recursively call this
	// function with the updated offset and limit
	return second.traverseByOffset(offset, limit, ascending, leavesOnly, cb)
}

// Only used in testing...
func (node *Node) lmd() *Node {
	if node.height == 0 {
		return node
	}
	return node.getLeftNode().lmd()
}

// Only used in testing...
func (node *Node) rmd() *Node {
	if node.height == 0 {
		return node
	}
	return node.getRightNode().rmd()
}

func maxInt8(a, b int8) int8 {
	if a > b {
		return a
	}
	return b
}

node_test.gno

package avl

import (
	"sort"
	"strings"
	"testing"

	"gno.land/p/nt/ufmt/v0"
)

func TestTraverseByOffset(t *testing.T) {
	const testStrings = `Alfa
Alfred
Alpha
Alphabet
Beta
Beth
Book
Browser`
	tt := []struct {
		name string
		asc  bool
	}{
		{"ascending", true},
		{"descending", false},
	}

	for _, tt := range tt {
		t.Run(tt.name, func(t *testing.T) {
			// use sl to insert the values, and reversed to match the values
			// we do this to ensure that the order of TraverseByOffset is independent
			// from the insertion order
			sl := strings.Split(testStrings, "\n")
			sort.Strings(sl)
			reversed := append([]string{}, sl...)
			reverseSlice(reversed)

			if !tt.asc {
				sl, reversed = reversed, sl
			}

			r := NewNode(reversed[0], nil)
			for _, v := range reversed[1:] {
				r, _ = r.Set(v, nil)
			}

			var result []string
			for i := 0; i < len(sl); i++ {
				r.TraverseByOffset(i, 1, tt.asc, true, func(n *Node) bool {
					result = append(result, n.Key())
					return false
				})
			}

			if !slicesEqual(sl, result) {
				t.Errorf("want %v got %v", sl, result)
			}

			for l := 2; l <= len(sl); l++ {
				// "slices"
				for i := 0; i <= len(sl); i++ {
					max := i + l
					if max > len(sl) {
						max = len(sl)
					}
					exp := sl[i:max]
					actual := []string{}

					r.TraverseByOffset(i, l, tt.asc, true, func(tr *Node) bool {
						actual = append(actual, tr.Key())
						return false
					})
					if !slicesEqual(exp, actual) {
						t.Errorf("want %v got %v", exp, actual)
					}
				}
			}
		})
	}
}

func TestTraverseByOffsetNegativeOffset(t *testing.T) {
	// a negative offset must be treated as 0, not silently drop the right
	// subtree. building {"a","b","c","d"} yields a tree whose root has two
	// inner children, exercising the traverseByOffset delta computation.
	keys := []string{"a", "b", "c", "d"}
	r := NewNode(keys[0], nil)
	for _, k := range keys[1:] {
		r, _ = r.Set(k, nil)
	}

	for _, offset := range []int{-1, -2, -100} {
		var got []string
		r.TraverseByOffset(offset, len(keys), true, true, func(n *Node) bool {
			got = append(got, n.Key())
			return false
		})
		if !slicesEqual(keys, got) {
			t.Errorf("offset %d: want %v got %v", offset, keys, got)
		}
	}
}

func TestHas(t *testing.T) {
	tests := []struct {
		name     string
		input    []string
		hasKey   string
		expected bool
	}{
		{
			"has key in non-empty tree",
			[]string{"C", "A", "B", "E", "D"},
			"B",
			true,
		},
		{
			"does not have key in non-empty tree",
			[]string{"C", "A", "B", "E", "D"},
			"F",
			false,
		},
		{
			"has key in single-node tree",
			[]string{"A"},
			"A",
			true,
		},
		{
			"does not have key in single-node tree",
			[]string{"A"},
			"B",
			false,
		},
		{
			"does not have key in empty tree",
			[]string{},
			"A",
			false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			result := tree.Has(tt.hasKey)

			if result != tt.expected {
				t.Errorf("Expected %v, got %v", tt.expected, result)
			}
		})
	}
}

func TestGet(t *testing.T) {
	tests := []struct {
		name         string
		input        []string
		getKey       string
		expectIdx    int
		expectVal    any
		expectExists bool
	}{
		{
			"get existing key",
			[]string{"C", "A", "B", "E", "D"},
			"B",
			1,
			nil,
			true,
		},
		{
			"get non-existent key (smaller)",
			[]string{"C", "A", "B", "E", "D"},
			"@",
			0,
			nil,
			false,
		},
		{
			"get non-existent key (larger)",
			[]string{"C", "A", "B", "E", "D"},
			"F",
			5,
			nil,
			false,
		},
		{
			"get from empty tree",
			[]string{},
			"A",
			0,
			nil,
			false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			idx, val, exists := tree.Get(tt.getKey)

			if idx != tt.expectIdx {
				t.Errorf("Expected index %d, got %d", tt.expectIdx, idx)
			}

			if val != tt.expectVal {
				t.Errorf("Expected value %v, got %v", tt.expectVal, val)
			}

			if exists != tt.expectExists {
				t.Errorf("Expected exists %t, got %t", tt.expectExists, exists)
			}
		})
	}
}

func TestGetByIndex(t *testing.T) {
	tests := []struct {
		name        string
		input       []string
		idx         int
		expectKey   string
		expectVal   any
		expectPanic bool
	}{
		{
			"get by valid index",
			[]string{"C", "A", "B", "E", "D"},
			2,
			"C",
			nil,
			false,
		},
		{
			"get by valid index (smallest)",
			[]string{"C", "A", "B", "E", "D"},
			0,
			"A",
			nil,
			false,
		},
		{
			"get by valid index (largest)",
			[]string{"C", "A", "B", "E", "D"},
			4,
			"E",
			nil,
			false,
		},
		{
			"get by invalid index (negative)",
			[]string{"C", "A", "B", "E", "D"},
			-1,
			"",
			nil,
			true,
		},
		{
			"get by invalid index (out of range)",
			[]string{"C", "A", "B", "E", "D"},
			5,
			"",
			nil,
			true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			if tt.expectPanic {
				defer func() {
					if r := recover(); r == nil {
						t.Errorf("Expected a panic but didn't get one")
					}
				}()
			}

			key, val := tree.GetByIndex(tt.idx)

			if !tt.expectPanic {
				if key != tt.expectKey {
					t.Errorf("Expected key %s, got %s", tt.expectKey, key)
				}

				if val != tt.expectVal {
					t.Errorf("Expected value %v, got %v", tt.expectVal, val)
				}
			}
		})
	}
}

func TestRemove(t *testing.T) {
	tests := []struct {
		name      string
		input     []string
		removeKey string
		expected  []string
	}{
		{
			"remove leaf node",
			[]string{"C", "A", "B", "D"},
			"B",
			[]string{"A", "C", "D"},
		},
		{
			"remove node with one child",
			[]string{"C", "A", "B", "D"},
			"A",
			[]string{"B", "C", "D"},
		},
		{
			"remove node with two children",
			[]string{"C", "A", "B", "E", "D"},
			"C",
			[]string{"A", "B", "D", "E"},
		},
		{
			"remove root node",
			[]string{"C", "A", "B", "E", "D"},
			"C",
			[]string{"A", "B", "D", "E"},
		},
		{
			"remove non-existent key",
			[]string{"C", "A", "B", "E", "D"},
			"F",
			[]string{"A", "B", "C", "D", "E"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			tree, _, _, _ = tree.Remove(tt.removeKey)

			result := make([]string, 0)
			tree.Iterate("", "", func(n *Node) bool {
				result = append(result, n.Key())
				return false
			})

			if !slicesEqual(tt.expected, result) {
				t.Errorf("want %v got %v", tt.expected, result)
			}
		})
	}
}

func TestTraverse(t *testing.T) {
	tests := []struct {
		name     string
		input    []string
		expected []string
	}{
		{
			"empty tree",
			[]string{},
			[]string{},
		},
		{
			"single node tree",
			[]string{"A"},
			[]string{"A"},
		},
		{
			"small tree",
			[]string{"C", "A", "B", "E", "D"},
			[]string{"A", "B", "C", "D", "E"},
		},
		{
			"large tree",
			[]string{"H", "D", "L", "B", "F", "J", "N", "A", "C", "E", "G", "I", "K", "M", "O"},
			[]string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			t.Run("iterate", func(t *testing.T) {
				var result []string
				tree.Iterate("", "", func(n *Node) bool {
					result = append(result, n.Key())
					return false
				})
				if !slicesEqual(tt.expected, result) {
					t.Errorf("want %v got %v", tt.expected, result)
				}
			})

			t.Run("ReverseIterate", func(t *testing.T) {
				var result []string
				tree.ReverseIterate("", "", func(n *Node) bool {
					result = append(result, n.Key())
					return false
				})
				expected := make([]string, len(tt.expected))
				copy(expected, tt.expected)
				for i, j := 0, len(expected)-1; i < j; i, j = i+1, j-1 {
					expected[i], expected[j] = expected[j], expected[i]
				}
				if !slicesEqual(expected, result) {
					t.Errorf("want %v got %v", expected, result)
				}
			})

			t.Run("TraverseInRange", func(t *testing.T) {
				var result []string
				start, end := "C", "M"
				tree.TraverseInRange(start, end, true, true, func(n *Node) bool {
					result = append(result, n.Key())
					return false
				})
				expected := make([]string, 0)
				for _, key := range tt.expected {
					if key >= start && key < end {
						expected = append(expected, key)
					}
				}
				if !slicesEqual(expected, result) {
					t.Errorf("want %v got %v", expected, result)
				}
			})

			t.Run("early termination", func(t *testing.T) {
				if len(tt.input) == 0 {
					return // Skip for empty tree
				}

				var result []string
				var count int
				tree.Iterate("", "", func(n *Node) bool {
					count++
					result = append(result, n.Key())
					return true // Stop after first item
				})

				if count != 1 {
					t.Errorf("Expected callback to be called exactly once, got %d calls", count)
				}
				if len(result) != 1 {
					t.Errorf("Expected exactly one result, got %d items", len(result))
				}
				if len(result) > 0 && result[0] != tt.expected[0] {
					t.Errorf("Expected first item to be %v, got %v", tt.expected[0], result[0])
				}
			})
		})
	}
}

func TestRotateWhenHeightDiffers(t *testing.T) {
	tests := []struct {
		name     string
		input    []string
		expected []string
	}{
		{
			"right rotation when left subtree is higher",
			[]string{"E", "C", "A", "B", "D"},
			[]string{"A", "B", "C", "D", "E"},
		},
		{
			"left rotation when right subtree is higher",
			[]string{"A", "C", "E", "D", "F"},
			[]string{"A", "C", "D", "E", "F"},
		},
		{
			"left-right rotation",
			[]string{"E", "A", "C", "B", "D"},
			[]string{"A", "B", "C", "D", "E"},
		},
		{
			"right-left rotation",
			[]string{"A", "E", "C", "B", "D"},
			[]string{"A", "B", "C", "D", "E"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			// perform rotation or balance
			tree = tree.balance()

			// check tree structure
			var result []string
			tree.Iterate("", "", func(n *Node) bool {
				result = append(result, n.Key())
				return false
			})

			if !slicesEqual(tt.expected, result) {
				t.Errorf("want %v got %v", tt.expected, result)
			}
		})
	}
}

func TestRotateAndBalance(t *testing.T) {
	tests := []struct {
		name     string
		input    []string
		expected []string
	}{
		{
			"right rotation",
			[]string{"A", "B", "C", "D", "E"},
			[]string{"A", "B", "C", "D", "E"},
		},
		{
			"left rotation",
			[]string{"E", "D", "C", "B", "A"},
			[]string{"A", "B", "C", "D", "E"},
		},
		{
			"left-right rotation",
			[]string{"C", "A", "E", "B", "D"},
			[]string{"A", "B", "C", "D", "E"},
		},
		{
			"right-left rotation",
			[]string{"C", "E", "A", "D", "B"},
			[]string{"A", "B", "C", "D", "E"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.input {
				tree, _ = tree.Set(key, nil)
			}

			tree = tree.balance()

			var result []string
			tree.Iterate("", "", func(n *Node) bool {
				result = append(result, n.Key())
				return false
			})

			if !slicesEqual(tt.expected, result) {
				t.Errorf("want %v got %v", tt.expected, result)
			}
		})
	}
}

func TestRemoveFromEmptyTree(t *testing.T) {
	var tree *Node
	newTree, _, val, removed := tree.Remove("NonExistent")
	if newTree != nil {
		t.Errorf("Removing from an empty tree should still be nil tree.")
	}
	if val != nil || removed {
		t.Errorf("Expected no value and removed=false when removing from empty tree.")
	}
}

func TestBalanceAfterRemoval(t *testing.T) {
	tests := []struct {
		name            string
		insertKeys      []string
		removeKey       string
		expectedBalance int
	}{
		{
			name:            "balance after removing right node",
			insertKeys:      []string{"B", "A", "D", "C", "E"},
			removeKey:       "E",
			expectedBalance: 0,
		},
		{
			name:            "balance after removing left node",
			insertKeys:      []string{"D", "B", "E", "A", "C"},
			removeKey:       "A",
			expectedBalance: 0,
		},
		{
			name:            "ensure no lean after removal",
			insertKeys:      []string{"C", "B", "E", "A", "D", "F"},
			removeKey:       "F",
			expectedBalance: -1,
		},
		{
			name:            "descending order insert, remove middle node",
			insertKeys:      []string{"E", "D", "C", "B", "A"},
			removeKey:       "C",
			expectedBalance: 0,
		},
		{
			name:            "ascending order insert, remove middle node",
			insertKeys:      []string{"A", "B", "C", "D", "E"},
			removeKey:       "C",
			expectedBalance: 0,
		},
		{
			name:            "duplicate key insert, remove the duplicated key",
			insertKeys:      []string{"C", "B", "C", "A", "D"},
			removeKey:       "C",
			expectedBalance: 1,
		},
		{
			name:            "complex rotation case",
			insertKeys:      []string{"H", "B", "A", "C", "E", "D", "F", "G"},
			removeKey:       "B",
			expectedBalance: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var tree *Node
			for _, key := range tt.insertKeys {
				tree, _ = tree.Set(key, nil)
			}

			tree, _, _, _ = tree.Remove(tt.removeKey)

			balance := tree.calcBalance()
			if balance != tt.expectedBalance {
				t.Errorf("Expected balance factor %d, got %d", tt.expectedBalance, balance)
			}

			if balance < -1 || balance > 1 {
				t.Errorf("Tree is unbalanced with factor %d", balance)
			}

			if errMsg := checkSubtreeBalance(t, tree); errMsg != "" {
				t.Errorf("AVL property violation after removal: %s", errMsg)
			}
		})
	}
}

func TestBSTProperty(t *testing.T) {
	var tree *Node
	keys := []string{"D", "B", "F", "A", "C", "E", "G"}
	for _, key := range keys {
		tree, _ = tree.Set(key, nil)
	}

	var result []string
	inorderTraversal(t, tree, &result)

	for i := 1; i < len(result); i++ {
		if result[i] < result[i-1] {
			t.Errorf("BST property violated: %s < %s (index %d)",
				result[i], result[i-1], i)
		}
	}
}

// inorderTraversal performs an inorder traversal of the tree and returns the keys in a list.
func inorderTraversal(t *testing.T, node *Node, result *[]string) {
	t.Helper()

	if node == nil {
		return
	}
	// leaf
	if node.height == 0 {
		*result = append(*result, node.key)
		return
	}
	inorderTraversal(t, node.leftNode, result)
	inorderTraversal(t, node.rightNode, result)
}

// checkSubtreeBalance checks if all nodes under the given node satisfy the AVL tree conditions.
// The balance factor of all nodes must be ∈ [-1, +1]
func checkSubtreeBalance(t *testing.T, node *Node) string {
	t.Helper()

	if node == nil {
		return ""
	}

	if node.IsLeaf() {
		// leaf node must be height=0, size=1
		if node.height != 0 {
			return ufmt.Sprintf("Leaf node %s has height %d, expected 0", node.Key(), node.height)
		}
		if node.size != 1 {
			return ufmt.Sprintf("Leaf node %s has size %d, expected 1", node.Key(), node.size)
		}
		return ""
	}

	// check balance factor for current node
	balanceFactor := node.calcBalance()
	if balanceFactor < -1 || balanceFactor > 1 {
		return ufmt.Sprintf("Node %s is unbalanced: balanceFactor=%d", node.Key(), balanceFactor)
	}

	// check height / size relationship for children
	left, right := node.getLeftNode(), node.getRightNode()
	expectedHeight := maxInt8(left.height, right.height) + 1
	if node.height != expectedHeight {
		return ufmt.Sprintf("Node %s has incorrect height %d, expected %d", node.Key(), node.height, expectedHeight)
	}
	expectedSize := left.Size() + right.Size()
	if node.size != expectedSize {
		return ufmt.Sprintf("Node %s has incorrect size %d, expected %d", node.Key(), node.size, expectedSize)
	}

	// recursively check the left/right subtree
	if errMsg := checkSubtreeBalance(t, left); errMsg != "" {
		return errMsg
	}
	if errMsg := checkSubtreeBalance(t, right); errMsg != "" {
		return errMsg
	}

	return ""
}

func slicesEqual(w1, w2 []string) bool {
	if len(w1) != len(w2) {
		return false
	}
	for i := 0; i < len(w1); i++ {
		if w1[i] != w2[i] {
			return false
		}
	}
	return true
}

func reverseSlice(ss []string) {
	for i := 0; i < len(ss)/2; i++ {
		j := len(ss) - 1 - i
		ss[i], ss[j] = ss[j], ss[i]
	}
}

tree.gno

package avl

type ITree interface {
	// read operations

	Size() int
	Has(key string) bool
	Get(key string) any
	GetByIndex(index int) (key string, value any)
	Iterate(start, end string, cb IterCbFn) bool
	ReverseIterate(start, end string, cb IterCbFn) bool
	IterateByOffset(offset int, count int, cb IterCbFn) bool
	ReverseIterateByOffset(offset int, count int, cb IterCbFn) bool

	// write operations

	Set(key string, value any) (updated bool)
	Remove(key string) (value any, removed bool)
}

type IterCbFn func(key string, value any) bool

//----------------------------------------
// Tree

// The zero struct can be used as an empty tree.
type Tree struct {
	node *Node
}

// NewTree creates a new empty AVL tree.
func NewTree() *Tree {
	return &Tree{
		node: nil,
	}
}

// Size returns the number of key-value pair in the tree.
func (tree *Tree) Size() int {
	return tree.node.Size()
}

// Has checks whether a key exists in the tree.
// It returns true if the key exists, otherwise false.
func (tree *Tree) Has(key string) (has bool) {
	return tree.node.Has(key)
}

// Get retrieves the value associated with the given key.
// It returns the value if the key exists, or nil if it doesn't.
// Note that a key stored with a nil value is indistinguishable
// from an absent key; use Has to check for existence.
// This allows for a simpler usage pattern with type assertions:
//
//	if value, ok := tree.Get("key").(MyType); ok {
//	    // use value
//	}
func (tree *Tree) Get(key string) any {
	_, value, _ := tree.node.Get(key)
	return value
}

// GetByIndex retrieves the key-value pair at the specified index in the tree.
// It returns the key and value at the given index.
func (tree *Tree) GetByIndex(index int) (key string, value any) {
	return tree.node.GetByIndex(index)
}

// Set inserts a key-value pair into the tree.
// If the key already exists, the value will be updated.
// It returns a boolean indicating whether the key was newly inserted or updated.
func (tree *Tree) Set(key string, value any) (updated bool) {
	newnode, updated := tree.node.Set(key, value)
	tree.node = newnode
	return updated
}

// Remove removes a key-value pair from the tree.
// It returns the removed value and a boolean indicating whether the key was found and removed.
func (tree *Tree) Remove(key string) (value any, removed bool) {
	newnode, _, value, removed := tree.node.Remove(key)
	tree.node = newnode
	return value, removed
}

// Iterate performs an in-order traversal of the tree within the specified key range.
// It calls the provided callback function for each key-value pair encountered.
// If the callback returns true, the iteration is stopped.
func (tree *Tree) Iterate(start, end string, cb IterCbFn) bool {
	return tree.node.TraverseInRange(start, end, true, true,
		func(node *Node) bool {
			return cb(node.Key(), node.Value())
		},
	)
}

// ReverseIterate performs a reverse in-order traversal of the tree within the specified key range.
// It calls the provided callback function for each key-value pair encountered.
// If the callback returns true, the iteration is stopped.
func (tree *Tree) ReverseIterate(start, end string, cb IterCbFn) bool {
	return tree.node.TraverseInRange(start, end, false, true,
		func(node *Node) bool {
			return cb(node.Key(), node.Value())
		},
	)
}

// IterateByOffset performs an in-order traversal of the tree starting from the specified offset.
// It calls the provided callback function for each key-value pair encountered, up to the specified count.
// If the callback returns true, the iteration is stopped.
func (tree *Tree) IterateByOffset(offset int, count int, cb IterCbFn) bool {
	return tree.node.TraverseByOffset(offset, count, true, true,
		func(node *Node) bool {
			return cb(node.Key(), node.Value())
		},
	)
}

// ReverseIterateByOffset performs a reverse in-order traversal of the tree starting from the specified offset.
// It calls the provided callback function for each key-value pair encountered, up to the specified count.
// If the callback returns true, the iteration is stopped.
func (tree *Tree) ReverseIterateByOffset(offset int, count int, cb IterCbFn) bool {
	return tree.node.TraverseByOffset(offset, count, false, true,
		func(node *Node) bool {
			return cb(node.Key(), node.Value())
		},
	)
}

// Verify that Tree implements TreeInterface
var _ ITree = (*Tree)(nil)

tree_test.gno

package avl

import "testing"

func TestNewTree(t *testing.T) {
	tree := NewTree()
	if tree.node != nil {
		t.Error("Expected tree.node to be nil")
	}
}

func TestTreeSize(t *testing.T) {
	tree := NewTree()
	if tree.Size() != 0 {
		t.Error("Expected empty tree size to be 0")
	}

	tree.Set("key1", "value1")
	tree.Set("key2", "value2")
	if tree.Size() != 2 {
		t.Error("Expected tree size to be 2")
	}
}

func TestTreeHas(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")

	if !tree.Has("key1") {
		t.Error("Expected tree to have key1")
	}

	if tree.Has("key2") {
		t.Error("Expected tree to not have key2")
	}
}

func TestTreeGet(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")

	value := tree.Get("key1")
	if value != "value1" {
		t.Error("Expected Get to return value1")
	}

	value = tree.Get("key2")
	if value != nil {
		t.Error("Expected Get to return nil for non-existent key")
	}
}

func TestTreeGetByIndex(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")
	tree.Set("key2", "value2")

	key, value := tree.GetByIndex(0)
	if key != "key1" || value != "value1" {
		t.Error("Expected GetByIndex(0) to return key1 and value1")
	}

	key, value = tree.GetByIndex(1)
	if key != "key2" || value != "value2" {
		t.Error("Expected GetByIndex(1) to return key2 and value2")
	}

	defer func() {
		if r := recover(); r == nil {
			t.Error("Expected GetByIndex to panic for out-of-range index")
		}
	}()
	tree.GetByIndex(2)
}

func TestTreeRemove(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")

	value, removed := tree.Remove("key1")
	if !removed || value != "value1" || tree.Size() != 0 {
		t.Error("Expected Remove to remove key-value pair")
	}

	_, removed = tree.Remove("key2")
	if removed {
		t.Error("Expected Remove to return false for non-existent key")
	}
}

func TestTreeIterate(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")
	tree.Set("key2", "value2")
	tree.Set("key3", "value3")

	var keys []string
	tree.Iterate("", "", func(key string, value any) bool {
		keys = append(keys, key)
		return false
	})

	expectedKeys := []string{"key1", "key2", "key3"}
	if !slicesEqual(keys, expectedKeys) {
		t.Errorf("Expected keys %v, got %v", expectedKeys, keys)
	}
}

func TestTreeReverseIterate(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")
	tree.Set("key2", "value2")
	tree.Set("key3", "value3")

	var keys []string
	tree.ReverseIterate("", "", func(key string, value any) bool {
		keys = append(keys, key)
		return false
	})

	expectedKeys := []string{"key3", "key2", "key1"}
	if !slicesEqual(keys, expectedKeys) {
		t.Errorf("Expected keys %v, got %v", expectedKeys, keys)
	}
}

func TestTreeIterateByOffset(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")
	tree.Set("key2", "value2")
	tree.Set("key3", "value3")

	var keys []string
	tree.IterateByOffset(1, 2, func(key string, value any) bool {
		keys = append(keys, key)
		return false
	})

	expectedKeys := []string{"key2", "key3"}
	if !slicesEqual(keys, expectedKeys) {
		t.Errorf("Expected keys %v, got %v", expectedKeys, keys)
	}
}

func TestTreeReverseIterateByOffset(t *testing.T) {
	tree := NewTree()
	tree.Set("key1", "value1")
	tree.Set("key2", "value2")
	tree.Set("key3", "value3")

	var keys []string
	tree.ReverseIterateByOffset(1, 2, func(key string, value any) bool {
		keys = append(keys, key)
		return false
	})

	expectedKeys := []string{"key2", "key1"}
	if !slicesEqual(keys, expectedKeys) {
		t.Errorf("Expected keys %v, got %v", expectedKeys, keys)
	}
}

func TestTreeReverseIterateByOffsetVaried(t *testing.T) {
	tree := NewTree()
	tree.Set("a", 1)
	tree.Set("b", 2)
	tree.Set("c", 3)
	tree.Set("d", 4)
	tree.Set("e", 5)

	// All keys in reverse: e d c b a
	cases := []struct {
		offset int
		limit  int
		want   []string
	}{
		{0, 5, []string{"e", "d", "c", "b", "a"}},
		{0, 1, []string{"e"}},
		{0, 3, []string{"e", "d", "c"}},
		{1, 2, []string{"d", "c"}},
		{2, 2, []string{"c", "b"}},
		{3, 5, []string{"b", "a"}},
		{4, 1, []string{"a"}},
		{4, 10, []string{"a"}},
		{5, 1, nil},
		{0, 0, nil},
		{10, 1, nil},
	}

	for _, tc := range cases {
		var got []string
		tree.ReverseIterateByOffset(tc.offset, tc.limit, func(key string, value any) bool {
			got = append(got, key)
			return false
		})
		if !slicesEqual(got, tc.want) {
			t.Errorf("ReverseIterateByOffset(%d, %d): got %v, want %v",
				tc.offset, tc.limit, got, tc.want)
		}
	}

	// Early termination: stop after 2 items from offset 1.
	var got []string
	tree.ReverseIterateByOffset(1, 5, func(key string, value any) bool {
		got = append(got, key)
		return len(got) >= 2
	})
	want := []string{"d", "c"}
	if !slicesEqual(got, want) {
		t.Errorf("ReverseIterateByOffset early stop: got %v, want %v", got, want)
	}
}