package main
import "fmt"
type Node struct {
val int
left *Node
right *Node
}
func (n *Node) Search(value int) *Node {
if n == nil {
return nil // reached leaf, not found
}
if value == n.val {
return n // found the value
} else if value < n.val {
return n.left.Search(value) // search left subtree
} else {
return n.right.Search(value) // search right subtree
}
}
func main() {
root := &Node{val: 5}
root.left = &Node{val: 3}
root.right = &Node{val: 7}
root.left.left = &Node{val: 2}
root.left.right = &Node{val: 4}
root.right.right = &Node{val: 8}
searchVal := 4
found := root.Search(searchVal)
if found != nil {
fmt.Printf("%d -> %d -> %d -> null (value %d found)\n", root.val, root.left.val, found.val, searchVal)
} else {
fmt.Printf("Value %d not found in BST\n", searchVal)
}
}
check if reached end of branch without finding value
found the node with the target value
go left if target is smaller than current node
go right if target is greater than current node
5 -> 3 -> 4 -> null (value 4 found)