0
0
DSA Javascriptprogramming~10 mins

BST Search Operation in DSA Javascript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start searching from the root node.

DSA Javascript
function searchBST(root, val) {
  let current = [1];
  while (current !== null) {
    if (val === current.val) return current;
    else if (val < current.val) current = current.left;
    else current = current.right;
  }
  return null;
}
Drag options to blanks, or click blank then click option'
Anull
Bval
Ccurrent
Droot
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing current to val instead of root
Setting current to null initially
2fill in blank
medium

Complete the code to move left when the search value is smaller than current node's value.

DSA Javascript
if (val < current.val) {
  current = [1];
}
Drag options to blanks, or click blank then click option'
Aroot.left
Bcurrent.right
Ccurrent.left
Droot.right
Attempts:
3 left
💡 Hint
Common Mistakes
Going to the right child instead of left
Using root instead of current
3fill in blank
hard

Fix the error in the condition to check if the current node is null.

DSA Javascript
while ([1] !== null) {
  if (val === current.val) return current;
  else if (val < current.val) current = current.left;
  else current = current.right;
}
Drag options to blanks, or click blank then click option'
Aroot
Bcurrent
Cval
Dcurrent.val
Attempts:
3 left
💡 Hint
Common Mistakes
Checking val instead of current
Checking current.val which can cause errors if current is null
4fill in blank
hard

Fill both blanks to complete the recursive search function for BST.

DSA Javascript
function searchBST(node, val) {
  if (node === null || node.val === [1]) return node;
  if (val < node.val) return searchBST(node.[2], val);
  else return searchBST(node.right, val);
}
Drag options to blanks, or click blank then click option'
Aval
Bleft
Cright
Dnode.val
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with node.val instead of val
Using right child instead of left for smaller values
5fill in blank
hard

Fill all three blanks to create a function that returns true if val exists in BST, false otherwise.

DSA Javascript
function existsInBST(root, val) {
  if (root === null) return false;
  if (root.val === [1]) return true;
  if (val < root.val) return existsInBST(root.[2], [3]);
  else return existsInBST(root.right, val);
}
Drag options to blanks, or click blank then click option'
Aval
Bleft
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true without comparison
Using right child for smaller values