GoTree/walk_test.go

44 lines
995 B
Go
Raw Normal View History

2024-09-30 17:26:54 +08:00
package tree
import (
"slices"
"testing"
)
func TestWalk(test *testing.T) {
t := Tree[any]{value: 1, children: []*Tree[any]{
{value: 2},
{value: 3, children: []*Tree[any]{
{value: 4},
{value: 5, children: []*Tree[any]{
{value: 6},
{value: nil, children: []*Tree[any]{
{value: nil},
}},
{value: 7, children: []*Tree[any]{
{value: 8},
}},
{value: 9},
{value: nil},
}},
{value: nil},
}},
{value: 10},
}}
var seq1, seq2 []any
t.DFS(func(value *any) {
seq1 = append(seq1, *value)
})
seq1Expect := []any{1, 2, 3, 4, 5, 6, nil, nil, 7, 8, 9, nil, nil, 10}
if !slices.Equal(seq1, seq1Expect) {
test.Errorf("DFS testing failed, expect: %v, actual: %v\n", seq1Expect, seq1)
}
t.BFS(func(value *any) {
seq2 = append(seq2, *value)
})
seq2Expect := []any{1, 2, 3, 10, 4, 5, nil, 6, nil, 7, 9, nil, nil, 8}
if !slices.Equal(seq2, seq2Expect) {
test.Errorf("BFS testing failed, expect: %v, actual: %v\n", seq2Expect, seq2)
}
}