Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a value into a Binary Search Tree (BST).
DSA Typescript
function insert(node: TreeNode | null, value: number): TreeNode {
if (node === null) {
return new TreeNode(value);
}
if (value [1] node.value) {
node.left = insert(node.left, value);
} else {
node.right = insert(node.right, value);
}
return node;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' causes wrong placement.
✗ Incorrect
In a BST, values less than the current node go to the left subtree.
2fill in blank
mediumComplete the code to search for a value in a BST.
DSA Typescript
function search(node: TreeNode | null, value: number): boolean {
if (node === null) return false;
if (value === node.value) return true;
if (value [1] node.value) {
return search(node.left, value);
} else {
return search(node.right, value);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing '<' and '>' leads to wrong search path.
✗ Incorrect
To search in BST, if value is less than node's value, search left subtree.
3fill in blank
hardFix the error in the code that checks if a tree is a BST.
DSA Typescript
function isBST(node: TreeNode | null, min: number | null = null, max: number | null = null): boolean {
if (node === null) return true;
if ((min !== null && node.value [1]= min) || (max !== null && node.value [2]= max)) {
return false;
}
return isBST(node.left, min, node.value) && isBST(node.right, node.value, max);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '>' alone misses equal values violating BST rules.
✗ Incorrect
Use '<=' and '>=' to ensure no duplicates violate BST property.
4fill in blank
hardFill both blanks to create a function that finds the minimum value in a BST.
DSA Typescript
function findMin(node: TreeNode | null): number | null {
if (node === null) return null;
while (node.[1] !== null) {
node = node.[2];
}
return node.value;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' instead of 'left' finds maximum, not minimum.
✗ Incorrect
The minimum value in a BST is found by going left until no more left child exists.
5fill in blank
hardFill all three blanks to implement in-order traversal of a BST that collects values in an array.
DSA Typescript
function inorderTraversal(node: TreeNode | null, result: number[] = []): number[] {
if (node !== null) {
inorderTraversal(node.[1], result);
result.push(node.[2]);
inorderTraversal(node.[3], result);
}
return result;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing order leads to incorrect traversal sequence.
✗ Incorrect
In-order traversal visits left subtree, node value, then right subtree.