I'm looking at this page on Rosettacode.org about tree traversal. I'm looking at the Go implementation, I'm fairly new to Go which is why I'd like your help.
Right at the beginning of the file, a struct is created. That's ok it makes sense so far. But the thing I don't understand is this:
type node struct {
value int
left, right *node
}
The left, right *node
part. I understand that the left, right variables are of type pointer to node. But I don't understand why, first-off I didn't know you could include the type you are creating, in this case node in the actual struct itself. And then I don't really understand why the code doesn't just say left, right node
.
func (n *node) iterPreorder(visit func(int)) {
if n == nil {
return
}
visit(n.value)
n.left.iterPreorder(visit)
n.right.iterPreorder(visit)
}
The next thing I don't get is, how the visit
variable can be of type func(int)
. Then I also don't get how you can use iterPreorder
within the function iterPreorder
.
And finally I'd just like to ask, what does this code do?
tree := &node{1,
&node{2,
&node{4,
&node{7, nil, nil},
nil},
&node{5, nil, nil}},
&node{3,
&node{6,
&node{8, nil, nil},
&node{9, nil, nil}},
nil}}
Thanks, here's a link to the full code over on Rosettacode.org.