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 findMin(node *Node) *Node {
current := node
for current.left != nil {
current = current.left
}
return current
}
func deleteNode(root *Node, key int) *Node {
if root == nil {
return nil
}
if key < root.val {
root.left = deleteNode(root.left, key) // traverse left subtree
} else if key > root.val {
root.right = deleteNode(root.right, key) // traverse right subtree
} else {
// found node to delete
if root.left == nil {
return root.right // replace node with right child
} else if root.right == nil {
return root.left // replace node with left child
}
// node with two children
minRight := findMin(root.right) // find inorder successor
root.val = minRight.val // copy successor's value
root.right = deleteNode(root.right, minRight.val) // delete successor
}
return root
}
func printInOrder(root *Node) {
if root == nil {
return
}
printInOrder(root.left)
fmt.Printf("%d -> ", root.val)
printInOrder(root.right)
}
func main() {
var root *Node
values := []int{5, 3, 7, 2, 4, 8}
for _, v := range values {
root = insert(root, v)
}
root = deleteNode(root, 3)
printInOrder(root)
fmt.Print("null\n")
}
if key < root.val {
root.left = deleteNode(root.left, key) // traverse left subtree
} else if key > root.val {
root.right = deleteNode(root.right, key) // traverse right subtree
} else {
search for node to delete by comparing key with current node value
if root.left == nil {
return root.right // replace node with right child
} else if root.right == nil {
return root.left // replace node with left child
}
handle cases where node has zero or one child by replacing it with child or nil
minRight := findMin(root.right) // find inorder successor
root.val = minRight.val // copy successor's value
root.right = deleteNode(root.right, minRight.val) // delete successor
for two children, replace node value with inorder successor and delete successor
2 -> 4 -> 5 -> 7 -> 8 -> null