Created
April 21, 2020 20:40
-
-
Save dantheman213/3e0b0057194a8d923eec37f4a43e927f to your computer and use it in GitHub Desktop.
Golang binary tree
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" | |
type Node struct { | |
Left, Right *Node | |
Value int64 | |
} | |
type BinarySearchTree struct { | |
Root *Node | |
} | |
func NewBinarySearchTree(rootValue int64) *BinarySearchTree { | |
tree := &BinarySearchTree{} | |
tree.Insert(tree.Root, rootValue) | |
return tree | |
} | |
func (t *BinarySearchTree) Insert(n *Node, value int64) { | |
if n == nil { | |
fmt.Printf("Inserted value: %d\n", value) | |
n = &Node{ | |
Value: value, | |
} | |
} else { | |
if value < n.Value { | |
t.Insert(n.Left, value) | |
} else if value > n.Value { | |
t.Insert(n.Right, value) | |
} | |
} | |
} | |
func (t *BinarySearchTree) ListAll(n *Node) { | |
if n != nil { | |
fmt.Printf("Value: %d\n", n.Value) | |
t.ListAll(n.Left) | |
t.ListAll(n.Right) | |
} | |
} | |
func main() { | |
fmt.Println("Hello World") | |
tree := NewBinarySearchTree(500) | |
tree.Insert(tree.Root, 350) | |
tree.Insert(tree.Root, 865) | |
tree.Insert(tree.Root, 251) | |
tree.Insert(tree.Root, 201) | |
tree.Insert(tree.Root, 101) | |
tree.Insert(tree.Root, 59) | |
tree.Insert(tree.Root, 20) | |
tree.Insert(tree.Root, 958) | |
tree.Insert(tree.Root, 632) | |
tree.Insert(tree.Root, 590) | |
tree.Insert(tree.Root, 1001) | |
tree.Insert(tree.Root, 999) | |
tree.ListAll(tree.Root) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment