From 9bc55def4454158866d80ad644b2895fea953655 Mon Sep 17 00:00:00 2001 From: c9s Date: Mon, 7 Jun 2021 01:38:07 +0800 Subject: [PATCH] rbt: fix deleting, copy value to the deleting node's memory --- pkg/types/rbtree.go | 8 ++++---- pkg/types/rbtree_test.go | 36 +++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/pkg/types/rbtree.go b/pkg/types/rbtree.go index d62b82e77..90f34aef2 100644 --- a/pkg/types/rbtree.go +++ b/pkg/types/rbtree.go @@ -57,8 +57,8 @@ func (tree *RBTree) Delete(key fixedpoint.Value) bool { } else { x = y.Right } - // fmt.Printf("x = %+v\n", y) + // fmt.Printf("x = %+v\n", y) x.Parent = y.Parent if y.Parent == tree.neel { @@ -69,14 +69,14 @@ func (tree *RBTree) Delete(key fixedpoint.Value) bool { y.Parent.Right = x } + // copy the data from the successor to the memory location of the deleting node if y != deleting { deleting.Key = y.Key + deleting.Value = y.Value } if y.Color == Black { - if x != nil { - tree.DeleteFixup(x) - } + tree.DeleteFixup(x) } tree.size-- diff --git a/pkg/types/rbtree_test.go b/pkg/types/rbtree_test.go index d030cc472..7425de382 100644 --- a/pkg/types/rbtree_test.go +++ b/pkg/types/rbtree_test.go @@ -8,12 +8,42 @@ import ( "github.com/stretchr/testify/assert" ) -func TestTree_InsertAndDelete(t *testing.T) { +func TestRBTree_InsertAndDelete(t *testing.T) { + tree := NewRBTree() + tree.Insert(fixedpoint.NewFromInt(10), 10) + tree.Insert(fixedpoint.NewFromInt(9), 9) + tree.Insert(fixedpoint.NewFromInt(12), 12) + tree.Insert(fixedpoint.NewFromInt(11), 11) + tree.Insert(fixedpoint.NewFromInt(13), 13) + + node := tree.Rightmost() + assert.Equal(t, fixedpoint.NewFromInt(13), node.Key) + + ok := tree.Delete(fixedpoint.NewFromInt(12)) + assert.True(t, ok, "should delete the node successfully") +} + +func TestRBTree_Rightmost(t *testing.T) { + tree := NewRBTree() + node := tree.Rightmost() + assert.Nil(t, node, "should be nil") + + tree.Insert(10, 10) + node = tree.Rightmost() + assert.Equal(t, fixedpoint.Value(10), node.Key) + + tree.Insert(12, 12) + tree.Insert(9, 9) + node = tree.Rightmost() + assert.Equal(t, fixedpoint.Value(12), node.Key) +} + +func TestRBTree_RandomInsertAndDelete(t *testing.T) { var keys []fixedpoint.Value tree := NewRBTree() for i := 1; i < 100; i++ { - v := fixedpoint.NewFromFloat(rand.Float64() * 100 + 1.0) + v := fixedpoint.NewFromFloat(rand.Float64()*100 + 1.0) keys = append(keys, v) tree.Insert(v, fixedpoint.NewFromFloat(float64(i))) } @@ -24,7 +54,7 @@ func TestTree_InsertAndDelete(t *testing.T) { } } -func TestTree_CopyInorder(t *testing.T) { +func TestRBTree_CopyInorder(t *testing.T) { tree := NewRBTree() for i := 1.0; i < 10.0; i += 1.0 { tree.Insert(fixedpoint.NewFromFloat(i*100.0), fixedpoint.NewFromFloat(i))