Last active
June 20, 2016 22:40
-
-
Save jakecoffman/3d8330cb1295c2fc72a3ecaf11edc2bb to your computer and use it in GitHub Desktop.
simple binary tree implementation and printer for those pesky interview problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: