package main
import "fmt"
type Node struct {
val int
left *Node
right *Node
}
func insert(root *Node, val int) *Node {
if root == nil {
return &Node{val: val}
}
if val < root.val {
root.left = insert(root.left, val)
} else {
root.right = insert(root.right, val)
}
return root
}
func floorCeil(root *Node, target int) (floor *int, ceil *int) {
var f, c *int
curr := root
for curr != nil {
if curr.val == target {
f = &curr.val
c = &curr.val
break
} else if curr.val > target {
c = &curr.val // update ceil candidate
curr = curr.left // go left to find smaller or equal
} else {
f = &curr.val // update floor candidate
curr = curr.right // go right to find bigger or equal
}
}
return f, c
}
func main() {
var root *Node
values := []int{8, 4, 12, 2, 6, 10, 14}
for _, v := range values {
root = insert(root, v)
}
floor, ceil := floorCeil(root, 5)
if floor != nil {
fmt.Printf("Floor: %d\n", *floor)
} else {
fmt.Println("Floor: nil")
}
if ceil != nil {
fmt.Printf("Ceil: %d\n", *ceil)
} else {
fmt.Println("Ceil: nil")
}
}
loop through nodes to find floor and ceil candidates
exact match found, floor and ceil are the same
else if curr.val > target {
current node value is bigger, update ceil and go left
current node value is smaller, update floor and go right