Complete the code to return the maximum value in a BST by moving right.
function findMax(root: TreeNode | null): number | null {
if (root === null) return null;
let current = root;
while (current.[1] !== null) {
current = current.right;
}
return current.val;
}In a BST, the maximum value is found by moving to the right child until there is no more right child.
Complete the code to recursively find the maximum value in a BST.
function findMaxRecursive(root: TreeNode | null): number | null {
if (root === null) return null;
if (root.[1] === null) return root.val;
return findMaxRecursive(root.right);
}The recursion stops when there is no right child, meaning the current node is the maximum.
Fix the error in the code to correctly find the maximum value in a BST iteratively.
function findMaxIterative(root: TreeNode | null): number | null {
if (root === null) return null;
let current = root;
while (current.[1] !== null) {
current = current.[1];
}
return current.val;
}To find the maximum, we must move right, not left.
Fill both blanks to create a function that finds the maximum value in a BST using recursion.
function findMax(root: TreeNode | null): number | null {
if (root === null) return null;
if (root.[1] === null) return root.val;
return findMax(root.[2]);
}The function checks if the right child is null to stop recursion, otherwise it continues to the right child.
Fill all three blanks to implement an iterative function that finds the maximum value in a BST.
function findMax(root: TreeNode | null): number | null {
if (root === null) return null;
let [1] = root;
while ([2].[3] !== null) {
[2] = [2].right;
}
return current.val;
}We use a variable 'current' to traverse the tree moving right until no more right child exists.