Skip to content

Commit

Permalink
new-feature: trie: add removeSameLeaf() to remove leaves with the sam…
Browse files Browse the repository at this point in the history
…e value
  • Loading branch information
drmingdrmer committed May 21, 2019
1 parent 7e480ed commit 5183902
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
53 changes: 53 additions & 0 deletions trie/trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,59 @@ func (r *Node) Squash() int {
return cnt
}

// removeSameLeaf removes leaf that has the same value as preceding leaf.
//
// a ------->e =1
// `>b------>f =2
// `>c->d->g =2 // "g" and "d" is removed, c has other child and is kept.
// `--->h =3
//
// Since 0.5.5
func (r *Node) removeSameLeaf() {

var prevValue interface{} = nil

// wrapped as a generalized tree
s := &trieStringly{tnode: r}

DepthFirst(s,
func(t Tree, parent, branch, node interface{}) {

n := node.(*Node)
needRemove := false

v, isLeaf := t.LeafVal(node)
if isLeaf {
if v == prevValue {
// same value no need to store
needRemove = true
} else {
prevValue = v
}
} else {
if len(n.Branches) == 0 {
needRemove = true
}
}

if needRemove && parent != nil && branch != nil {
p := parent.(*Node)
b := branch.(int)

delete(p.Children, b)

for i, bb := range p.Branches {
if bb == b {
p.Branches = append(p.Branches[:i], p.Branches[i+1:]...)
return
}
}
r.NodeCnt--

}
})
}

// Search for `key` in a Trie.
//
// It returns 3 values of:
Expand Down
41 changes: 41 additions & 0 deletions trie/trie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/openacid/errors"
"github.com/openacid/slim/benchhelper"
"github.com/stretchr/testify/require"
)

func TestTrie(t *testing.T) {
Expand Down Expand Up @@ -527,3 +528,43 @@ func TestToStrings(t *testing.T) {
t.Fatalf("expect: \n%v\n; but: \n%v\n", expect, trie.String())
}
}

func TestTrie_removeSameLeaf(t *testing.T) {

ta := require.New(t)

var keys = [][]byte{
{'a', 'b', 'c'},
{'a', 'b', 'c', 'd'},
{'a', 'b', 'd'},
{'a', 'b', 'd', 'e'},
{'b', 'c'},
{'b', 'c', 'd'},
{'b', 'c', 'd', 'e'},
{'c', 'd', 'e'},
}
var values = []int{0, 0, 0, 3, 4, 5, 5, 5}

want := `
*2
-097->
-098->*2
-099->
-00$->=0
-100->
-101->
-00$->=3
-098->
-099->*2
-00$->=4
-100->
-00$->=5`[1:]

trie, err := NewTrie(keys, values, false)
ta.Nil(err)

trie.removeSameLeaf()

ta.Equal(want, trie.String())
ta.Equal(13, trie.NodeCnt)
}

0 comments on commit 5183902

Please sign in to comment.