Skip to content

Commit

Permalink
Lazy allocate root and handle cases with null root
Browse files Browse the repository at this point in the history
  • Loading branch information
caojoshua committed Mar 10, 2024
1 parent 64de71c commit 1e5fa13
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
8 changes: 7 additions & 1 deletion structure/tree/btree.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func NewBTree[T constraints.Ordered](maxKeys int) *BTree[T] {
panic("Must be >= 3 keys")
}
return &BTree[T]{
root: NewBTreeNode[T](maxKeys, true),
root: nil,
maxKeys: maxKeys,
}
}
Expand Down Expand Up @@ -72,6 +72,9 @@ func (node *BTreeNode[T]) Search(key T) bool {
}

func (tree *BTree[T]) Search(key T) bool {
if tree.root == nil {
return false;

Check failure on line 76 in structure/tree/btree.go

View workflow job for this annotation

GitHub Actions / Code style and tests

File is not `gofmt`-ed with `-s` (gofmt)
}
return tree.root.Search(key)
}

Expand Down Expand Up @@ -342,6 +345,9 @@ func (node *BTreeNode[T]) Delete(tree *BTree[T], key T) {
}

func (tree *BTree[T]) Delete(key T) {
if tree.root == nil {
return
}
tree.root.Delete(tree, key)
if tree.root.numKeys == 0 {
tree.root = tree.root.children[0]
Expand Down
28 changes: 28 additions & 0 deletions structure/tree/btree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ func TestBTreeIncreasing(t *testing.T) {
for _, maxKeys := range maxKeysCases {
for _, size := range sizes {
tree := bt.NewBTree[int](maxKeys)
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")

Check failure on line 16 in structure/tree/btree_test.go

View workflow job for this annotation

GitHub Actions / Code style and tests

File is not `gofmt`-ed with `-s` (gofmt)
}
for i := 0; i < size; i++ {
tree.Insert(i)
}
Expand Down Expand Up @@ -45,6 +48,9 @@ func TestBTreeDecreasing(t *testing.T) {
for _, maxKeys := range maxKeysCases {
for _, size := range sizes {
tree := bt.NewBTree[int](maxKeys)
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")
}
for i := size - 1; i >= 0; i-- {
tree.Insert(i)
}
Expand Down Expand Up @@ -80,6 +86,9 @@ func TestBTreeRandom(t *testing.T) {
rnd := rand.New(rand.NewSource(0))
tree := bt.NewBTree[int](maxKeys)
nums := rnd.Perm(size)
if tree.Search(0) {
t.Errorf("Tree expected to contain 0")
}
for i := 0; i < size; i++ {
tree.Insert(nums[i])
}
Expand All @@ -103,3 +112,22 @@ func TestBTreeRandom(t *testing.T) {
}
}
}

func TestBTreeDeleteEverything(t *testing.T) {
tree := bt.NewBTree[int](4)
size := 128
for i := 0; i < size; i++ {
tree.Insert(i)
}
for i := 0; i < size; i++ {
tree.Delete(i)
}
tree.Delete(-1)
tree.Delete(1000)

for i := 0; i < size; i++ {
if tree.Search(i) {
t.Errorf("Tree not expected to contain %d", i)
}
}
}

0 comments on commit 1e5fa13

Please sign in to comment.