diff --git a/pkg/trie/trie.go b/pkg/trie/trie.go index da7f989..217eefc 100644 --- a/pkg/trie/trie.go +++ b/pkg/trie/trie.go @@ -94,7 +94,9 @@ func (t *BinaryTrie[T]) IsBranch() bool { return t.GetSibling() != nil } -func (t *BinaryTrie[T]) Remove() { +// Detach will discount the node from the tree +// if there is no reference to the node, it will be GC'ed +func (t *BinaryTrie[T]) Detach() { if !t.isRoot() { t.Parent.Children[t.GetPos()] = nil } else { @@ -103,12 +105,15 @@ func (t *BinaryTrie[T]) Remove() { } // removes current node, and the whole branch +// and return the parent of last removed node // this will remove any parent that had only one child until it // reaches a parant that have 2 children (beginning of the branch) // node(branch) -->node-->node-->node // // l>node-->node-->node (Dutch) // [remove all the branch] +// +// will return the branch node parent func (t *BinaryTrie[T]) DetachBranch(limit int) *BinaryTrie[T] { // if it has children if t.isRoot() { @@ -124,9 +129,9 @@ func (t *BinaryTrie[T]) DetachBranch(limit int) *BinaryTrie[T] { return !next.IsBranch() && next.depth > limit }) - nearestBranchedNode.Remove() + nearestBranchedNode.Detach() - return t + return nearestBranchedNode.Parent } // checks if the node is a leaf (has no children). diff --git a/pkg/trie/trie_test.go b/pkg/trie/trie_test.go index dfdeba9..7fdc44d 100644 --- a/pkg/trie/trie_test.go +++ b/pkg/trie/trie_test.go @@ -129,7 +129,7 @@ func TestGetSibling(t *testing.T) { assert.Nil(t, leafs[1].GetSibling()) } -func TestAddSibling(t *testing.T) { +func TestAddSiblingIfNotExist(t *testing.T) { paths := []string{"0010", "0011", "00111"} root := NewTrie() generateTrieAs(paths, root) @@ -155,6 +155,7 @@ func TestAddSiblingIfExist(t *testing.T) { assert.NotEqual(t, sibling, leafs[0].GetSibling()) } +func TestDetach(t *testing.T) { paths := []string{"0010", "0011"} root := NewTrie() generateTrieAs(paths, root) @@ -164,20 +165,20 @@ func TestAddSiblingIfExist(t *testing.T) { }, root.GetLeafsPaths()) leafs := root.GetLeafs() - leafs[0].Remove() + leafs[0].Detach() newLeafs := root.GetLeafs() assert.Equal(t, 1, len(newLeafs)) assert.Equal(t, []int{0, 0, 1, 1}, newLeafs[0].GetPath()) - leafs[1].Remove() + leafs[1].Detach() newLeafs = root.GetLeafs() assert.Equal(t, 1, len(newLeafs)) assert.Equal(t, []int{0, 0, 1}, newLeafs[0].GetPath()) } -func TestDetach(t *testing.T) { +func TestDetachBranch(t *testing.T) { //(0)-> 0|0|1[0] // (1)->|1|0|0|0|0[0] if we detach at last bit of the branch, the whole branch should be deleted paths := []string{