Skip to content

Instantly share code, notes, and snippets.

@jakecoffman
Last active June 20, 2016 22:40
Show Gist options
  • Save jakecoffman/3d8330cb1295c2fc72a3ecaf11edc2bb to your computer and use it in GitHub Desktop.
Save jakecoffman/3d8330cb1295c2fc72a3ecaf11edc2bb to your computer and use it in GitHub Desktop.
simple binary tree implementation and printer for those pesky interview problems
package main
import (
"fmt"
"strings"
)
type BinaryTree struct {
Node int // or whatever
Left *BinaryTree
Right *BinaryTree
}
func (t BinaryTree) String() string {
return t.pretty(0)
}
func (t BinaryTree) pretty(depth int) string {
str := leftPad(fmt.Sprintf("<tree value='%v'>", t.Node), depth)
if t.Left != nil {
str += "\n" + t.Left.pretty(depth+1)
}
if t.Right != nil {
str += "\n" + t.Right.pretty(depth+1)
}
if t.Right == nil && t.Left == nil {
str += "</tree>"
} else {
str += "\n" + leftPad("</tree>", depth)
}
return str
}
type Tree struct {
Node int // or whatever
Children []*Tree
}
func (t Tree) String() string {
return t.pretty(0)
}
func (t Tree) pretty(depth int) string {
str := leftPad(fmt.Sprintf("<tree value='%v'>", t.Node), depth)
hasChildren := false
for _, child := range t.Children {
hasChildren = true
str += "\n" + child.pretty(depth+1)
}
if !hasChildren {
str += "</tree>"
} else {
str += "\n" + leftPad("</tree>", depth)
}
return str
}
func leftPad(s string, depth int) string {
return strings.Repeat(" ", depth) + s
}
func main() {
btree := &BinaryTree{Node: 0}
btree.Left = &BinaryTree{Node: -1}
btree.Right = &BinaryTree{Node: 1, Right: &BinaryTree{Node: 2}}
fmt.Println(btree)
tree := &Tree{
Node: 0,
Children: []*Tree{
&Tree{Node: -1},
&Tree{Node: 1, Children: []*Tree{
&Tree{Node: 2},
}},
},
}
fmt.Println(tree)
}
@jakecoffman
Copy link
Author

jakecoffman commented Jun 20, 2016

Output:

<tree value='0'>
 <tree value='-1'></tree>
 <tree value='1'>
  <tree value='2'></tree>
 </tree>
</tree>
<tree value='0'>
 <tree value='-1'></tree>
 <tree value='1'>
  <tree value='2'></tree>
 </tree>
</tree>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment