Skip to content

Instantly share code, notes, and snippets.

@manju4ever
Last active August 12, 2020 20:39
Show Gist options
  • Select an option

  • Save manju4ever/5f0aaf9954884dfc55a1db7c955bbd8d to your computer and use it in GitHub Desktop.

Select an option

Save manju4ever/5f0aaf9954884dfc55a1db7c955bbd8d to your computer and use it in GitHub Desktop.
Binary Search Tree in GO
package main
import "fmt"
const DEBUG bool = true
type Leaf struct {
value int
left *Leaf
right *Leaf
}
type Tree interface {
insert(node *Leaf)
contains(value int)
remove(node *Leaf)
}
type BST struct {
root *Leaf
}
func (tree *BST) Insert(value int) *BST {
root := tree.root
if root == nil {
root = &Leaf{value, nil, nil}
return tree
}
for root != nil {
if value <= root.value {
if root.left == nil {
root.left = &Leaf{value, nil, nil}
return tree
}
root = root.left
}
if value >= root.value {
if root.right == nil {
root.right = &Leaf{value, nil, nil}
return tree
}
root = root.right
}
}
return tree
}
func Finder(leaf *Leaf, query int) (current *Leaf, parent *Leaf) {
currentNode, parentNode := leaf, &Leaf{}
for currentNode != nil {
if DEBUG == true {
fmt.Printf("\n[DEBUG] Finder: At current: %d, parent: %d\n", currentNode.value, parentNode.value)
}
if currentNode != nil && currentNode.value == query {
return currentNode, parentNode
}
if query < currentNode.value {
parentNode = currentNode
currentNode = currentNode.left
}
if query > currentNode.value {
parentNode = currentNode
currentNode = currentNode.right
}
}
return nil, nil
}
func (tree *BST) Contains(query int) bool {
foundNode, parentNode := Finder(tree.root, query)
if DEBUG == true {
parentVal := -1
if parentNode != nil {
parentVal = parentNode.value
}
fmt.Printf("\n[DEBUG] Search: query: %d, Found: %v, Parent: %v\n", query, (foundNode != nil), parentVal)
}
return foundNode != nil
}
func (tree *BST) FindMaxLeft(start *Leaf) *Leaf {
if start == nil {
return &Leaf{}
}
current, maxValue := start, start.value
for current != nil {
if maxValue < current.value {
maxValue = current.value
current = current.left
}
}
return current
}
func (tree *BST) Remove(value int) {
}
func Inorder(tree *Leaf) {
if tree == nil {
return
}
print(tree.value, " ")
Inorder(tree.left)
Inorder(tree.right)
}
func main() {
tree := BST{&Leaf{10, nil, nil}}
tree.Insert(12).Insert(13).Insert(17).Insert(15).Insert(16)
Inorder(tree.root)
tree.Contains(19)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment