package main
import "fmt"
type Node struct {
val int
left *Node
right *Node
}
func searchBST(root *Node, target int) *Node {
curr := root
for curr != nil {
if target == curr.val {
return curr // found target
} else if target < curr.val {
curr = curr.left // go left for smaller values
} else {
curr = curr.right // go right for bigger values
}
}
return nil // target not found
}
func main() {
root := &Node{val: 10}
root.left = &Node{val: 5}
root.right = &Node{val: 15}
root.left.left = &Node{val: 3}
root.left.right = &Node{val: 7}
root.right.right = &Node{val: 20}
target := 7
found := searchBST(root, target)
if found != nil {
fmt.Printf("Found %d\n", found.val)
} else {
fmt.Printf("Value %d not found\n", target)
}
}
start search at root node
continue until we find target or reach end
check if current node is target
return curr // found target
stop search and return node
else if target < curr.val {
go left if target smaller than current
curr = curr.left // go left for smaller values
move to left child
go right if target bigger than current
curr = curr.right // go right for bigger values
move to right child