I am trying to implement a tree in Go.
type BinaryNode struct {
left *BinaryNode
right *BinaryNode
data int
}
type BinaryTree struct {
root *BinaryNode
}
Now to insert elements , I have an insert func,
func (t *BinaryNode) insertNode(d int) {
fmt.Printf("%+v\n", t)
if t == nil {
t = &BinaryNode{
data: d,
left: nil,
right: nil,
}
fmt.Printf("%+v inside insert\n", t)
} else {
if d <= t.data {
t.left.insertNode(d)
} else {
t.right.insertNode(d)
}
}
}
If the pointer is nil, create a new node, if not look for left or right, according to the data. In my main function , i am trying simple few steps :
func main() {
tree1 := &BinaryTree{
root: nil,
}
tree1.root.insertNode(3)
fmt.Printf("%+v\n", tree1.root)
}
What i expect to see is a tree with root value 3. but i do not see any. Instead I get:
<nil>
&{left:<nil> right:<nil> data:3} inside insert
<nil>
From what I have understood, if the struct pointer is used for methods, a copy is not made. In that case, the modification should persist.
What have I missed here?