Skip to content

Commit

Permalink
avl: fix t.Size() crash on empty tree
Browse files Browse the repository at this point in the history
  • Loading branch information
yoursunny committed Apr 6, 2022
1 parent 51896d3 commit 8715f40
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
10 changes: 3 additions & 7 deletions avl/avl.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,8 @@ func (n *node[K, V]) findSmallest() *node[K, V] {
}

func (n *node[K, V]) size() int {
s := 1
if n.left != nil {
s += n.left.size()
}
if n.right != nil {
s += n.left.size()
if n == nil {
return 0
}
return s
return 1 + n.left.size() + n.right.size()
}
16 changes: 10 additions & 6 deletions avl/avl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import (
"github.com/zyedidia/generic/avl"
)

func checkeq[K any, V comparable](cm *avl.Tree[K, V], get func(k K) (V, bool), t *testing.T) {
func checkeq[K any, V comparable](cm *avl.Tree[K, V], n int, get func(k K) (V, bool), t *testing.T) {
if sz := cm.Size(); sz != n {
t.Fatalf("size mismatch: %d != %d", sz, n)
}
cm.Each(func(key K, val V) {
if ov, ok := get(key); !ok {
t.Fatalf("key %v should exist", key)
Expand All @@ -21,10 +24,14 @@ func checkeq[K any, V comparable](cm *avl.Tree[K, V], get func(k K) (V, bool), t

func TestCrossCheck(t *testing.T) {
stdm := make(map[int]int)
get := func(k int) (int, bool) {
v, ok := stdm[int(k)]
return v, ok
}
tree := avl.New[int, int](g.Less[int])
checkeq(tree, len(stdm), get, t)

const nops = 1000

for i := 0; i < nops; i++ {
key := rand.Intn(100)
val := rand.Int()
Expand All @@ -44,10 +51,7 @@ func TestCrossCheck(t *testing.T) {
tree.Remove(del)
}

checkeq(tree, func(k int) (int, bool) {
v, ok := stdm[int(k)]
return v, ok
}, t)
checkeq(tree, len(stdm), get, t)
}
}

Expand Down

0 comments on commit 8715f40

Please sign in to comment.