Complete the code to insert a value into a Binary Search Tree (BST).
function insertNode(root, value) {
if (root === null) {
return { val: value, left: null, right: null };
}
if (value [1] root.val) {
root.left = insertNode(root.left, value);
} else {
root.right = insertNode(root.right, value);
}
return root;
}In a BST, values less than the current node go to the left subtree, so we use < to decide where to insert.
Complete the code to search for a value in a BST.
function searchBST(root, target) {
if (root === null) return false;
if (root.val === target) return true;
if (target [1] root.val) {
return searchBST(root.left, target);
} else {
return searchBST(root.right, target);
}
}To search in BST, if target is less than current node, search left subtree.
Complete the code to find the minimum value in a BST.
function findMin(root) {
while (root.[1] !== null) {
root = root.left;
}
return root.val;
}The minimum value in a BST is located at the leftmost node. Therefore, we keep moving left while root.left !== null.
Fill both blanks to create a function that counts nodes in a BST.
function countNodes(root) {
if (root === null) return 0;
return 1 + countNodes(root.[1]) + countNodes(root.[2]);
}To count all nodes, recursively count left and right subtrees using root.left and root.right.
Fill all three blanks to create a function that deletes a node from a BST.
function deleteNode(root, key) {
if (root === null) return root;
if (key [1] root.val) {
root.left = deleteNode(root.left, key);
} else if (key [2] root.val) {
root.right = deleteNode(root.right, key);
} else {
if (root.left === null) return root.[3];
else if (root.right === null) return root.left;
let minNode = findMinNode(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, minNode.val);
}
return root;
}To delete a node, compare key with root.val using < and > to traverse left or right. If node has only right child, return root.right.