I've defined a go struct of Trie data structure.
type Node struct {
Val rune
IsWord bool
IsRoot bool
Parent *Node
Children map[rune]*Node
}
type Trie struct {
Root *Node
}
trie := algorithms.InitTrie()
However, it raises an error
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
runtime stack:
runtime.throw(0x10e9426, 0xe)
/usr/local/go/src/runtime/panic.go:605 +0x95
runtime.newstack(0x0)
/usr/local/go/src/runtime/stack.go:1050 +0x6e1
runtime.morestack()
/usr/local/go/src/runtime/asm_amd64.s:415 +0x86
When I insert some words and save it into json file.
fmt.Println(json.Marshal(&trie))
The problem is that each Node
has a reference to it's parent, as well as to it's children. So when it encodes a child, for the parent field, it encodes the parent again, and for that parent, it encodes the child again, etc. A simple solution would be to simply not use the Parent
field when encoding
Parent *Node `json:"-"`
This will prevent the cycle.