Complete the code to create a new BST node with the given key.
func newNode(key int) *Node {
return &Node{
key: [1],
left: nil,
right: nil,
}
}The new node's key should be set to the given key parameter.
Complete the code to find the minimum value node in a BST.
func minValueNode(node *Node) *Node {
current := node
for current.left != [1] {
current = current.left
}
return current
}We loop until current.left is nil, which means we reached the smallest node.
Fix the error in the delete function to correctly delete a node with two children.
func deleteNode(root *Node, key int) *Node {
if root == nil {
return root
}
if key < root.key {
root.left = deleteNode(root.left, key)
} else if key > root.key {
root.right = deleteNode(root.right, key)
} else {
if root.left == nil {
return root.right
} else if root.right == nil {
return root.left
}
temp := [1](root.right)
root.key = temp.key
root.right = deleteNode(root.right, temp.key)
}
return root
}To delete a node with two children, replace it with the minimum node in the right subtree.
Fill both blanks to complete the in-order traversal function that prints BST keys.
func inorder(root *Node) {
if root != [1] {
inorder(root.[2])
fmt.Print(root.key, " -> ")
inorder(root.right)
}
}Check if root is not nil, then recursively traverse the left subtree first.
Fill all three blanks to complete the delete function that handles all cases correctly.
func deleteNode(root *Node, key int) *Node {
if root == [1] {
return root
}
if key < root.key {
root.left = deleteNode(root.left, [2])
} else if key > root.key {
root.right = deleteNode(root.right, key)
} else {
if root.left == nil {
return root.right
} else if root.right == nil {
return root.left
}
temp := minValueNode(root.right)
root.key = temp.key
root.right = deleteNode(root.right, [3])
}
return root
}Check if root is nil to stop recursion. Pass the key when going left. Use temp.key when deleting the successor node.