Exercise 7.3: Implement a String method for the *tree type in Gopl.io/ch4/treesort (§4.4) to show a sequence of values for the tree type.
Package Mainimport ("FMT" "bytes") Func main () {//definition array arr:=[...] int{6,2,1,3,4,5} var t *tree for I:=0;i<len (arr); i++{T=add (T,arr[i])}/ /t1:=sort (arr[:],t)//fmt. Println (arr) fmt. Println (t)}/* Exercise 7.3: Implement a String method for the *tree type in Gopl.io/ch4/treesort (§4.4) to display a sequence of values for the tree type. */func (t *tree) String () string{var buf bytes. Buffer var data []int data=appendvalues (data,t) buf. WriteByte (' {') for _,v:=range data{if buf. Len () > Len ("{") {buf. WriteByte (")}//Focus: Using the interface Convention FMT. fprintf (&buf, "%d", V)} buf. WriteByte ('} ') return BUF. String ()}type tree struct {value int left, right *tree}//sort sorts values in place.func sort (values []int, Root *tree) *tree {//var root *tree for _, V: = range values {root = Add (root, V)} FMT. Println (Root) appendvalues (values[:0], root) return root}//Appendvalues appends the elements of T to values in order//and R Eturns the resulting slice.func appendvalues (values []int, T *tree) []int {if t! = Nil {values = Appendvalues ( values, t.left) values = Append (values, t.value) values = Appendvalues (values, t.right)} return value S}func Add (t *tree, value int) *tree {if T = = nil {//equivalent to return &tree{value:value}. t = new (tree) T.value = value return T} if value < T.value {T.left = Add (t.left, value) } else {t.right = Add (t.right, value)} return T}
Daily Go Language Bible-Interface Conventions Exercise 2