/* * Pointers in Go * In a value-model lang you need pointers to have a recursive structure like a tree. * * @author gtowell * Created: Aug 23, 2021 */ package main import "fmt" // node is a tree. It has pointers to two other nodes. type treenode struct { payload int right *treenode left *treenode } // recursive method on treenode to do in-order printing // Methods can be on pointers as well as the thing itself! func (tn *treenode) ptn() { if (tn==nil) { return } else { tn.left.ptn() fmt.Printf("%d\n", tn.payload) tn.right.ptn() } } // Recursive Method on treenode to add a new value into tree func (tp *treenode) appendToTree(val int) { if tp.payload <= val { if tp.right == nil { tp.right = new (treenode) tp.right.payload = val } else { tp.right.appendToTree(val) } } else { if tp.left == nil { tp.left = new(treenode) tp.left.payload = val } else { tp.left.appendToTree(val) } } } // a struct to hold the root of a tree. // Kind of annoying, but doing it this way means that the thing // holding the root never changes even if the root changes. // Of course, once set root will only change if I wrote delete or balance type tree struct { root *treenode } // Method to print the tree // Question -- why have this as a method on pointer? func (mt *tree) ptree() { if mt.root == nil { fmt.Println("Empty tree") } else { mt.root.ptn() } } // Method to add to tree. // Question -- why have this as a method on pointer? func (mt *tree) addToTree(newval int) { if mt.root == nil { mt.root = new(treenode) mt.root.payload = newval } else { mt.root.appendToTree(newval) } } func main() { mytree := new(tree) mytree.addToTree( 8) mytree.addToTree(16) mytree.addToTree(4) mytree.addToTree(12) mytree.addToTree(2) mytree.ptree() }