Last active
April 7, 2016 09:37
-
-
Save anthonynsimon/e098c3696588141a6b54183dd8245874 to your computer and use it in GitHub Desktop.
Simple Binary Tree in Go
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 btree | |
import ( | |
"fmt" | |
) | |
type BinaryTree struct { | |
Root *Node | |
NumberOfIterations int | |
} | |
type Node struct { | |
Value int | |
Left *Node | |
Right *Node | |
} | |
func (btree *BinaryTree) Traverse() { | |
traverseHelper(btree.Root) | |
} | |
// Depth-first-search in-order traversal | |
func traverseHelper(node *Node) { | |
if node.Left != nil { | |
traverseHelper(node.Left) | |
} | |
fmt.Println(node.Value) | |
if node.Right != nil { | |
traverseHelper(node.Right) | |
} | |
} | |
func (btree *BinaryTree) Generate(list []int) { | |
for _, item := range list { | |
btree.Insert(item) | |
} | |
} | |
func (btree *BinaryTree) Insert(value int) { | |
if btree.Root == nil { | |
btree.NumberOfIterations = 0 | |
btree.Root = &Node{value, nil, nil} | |
} | |
current := btree.Root | |
for { | |
btree.NumberOfIterations += 1 | |
if current.Value > value { | |
if current.Left == nil { | |
current.Left = &Node{value, nil, nil} | |
break | |
} | |
current = current.Left | |
} else { | |
if current.Right == nil { | |
current.Right = &Node{value, nil, nil} | |
break | |
} | |
current = current.Right | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment