0
0
DSA Javascriptprogramming~30 mins

BST Search Operation in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
BST Search Operation
📖 Scenario: You are working with a simple phone book application that stores contacts in a Binary Search Tree (BST). Each contact has a unique phone number as the key.You want to find if a particular phone number exists in the phone book.
🎯 Goal: Build a program that creates a BST with given phone numbers, sets a target phone number to search, performs the search operation, and prints whether the number is found or not.
📋 What You'll Learn
Create a BST node class with value, left, and right properties
Manually create a BST with the exact phone numbers: 50, 30, 70, 20, 40, 60, 80
Create a variable target with the phone number to search: 60
Write a function searchBST that takes the root node and the target value and returns true if found, otherwise false
Print Found if the target is in the BST, else print Not Found
💡 Why This Matters
🌍 Real World
BSTs are used in phone books, contact lists, and databases to quickly find information by key.
💼 Career
Understanding BST search is important for software engineers working with data storage, search engines, and optimization.
Progress0 / 4 steps
1
Create BST nodes and build the tree
Create a class called Node with a constructor that takes value and sets left and right to null. Then create nodes with values 50, 30, 70, 20, 40, 60, and 80. Connect them to form the BST as shown: 50 is root, 30 is left child of 50, 70 is right child of 50, 20 is left child of 30, 40 is right child of 30, 60 is left child of 70, and 80 is right child of 70.
DSA Javascript
Hint

Define the Node class first. Then create the root node with value 50. Attach left and right children as described.

2
Set the target phone number to search
Create a variable called target and set it to the number 60.
DSA Javascript
Hint

Just create a variable named target and assign it the value 60.

3
Write the search function for BST
Write a function called searchBST that takes two parameters: node and target. It should return true if target is found in the BST starting at node, otherwise false. Use the BST property: if target is less than node.value, search the left subtree; if greater, search the right subtree; if equal, return true. If node is null, return false.
DSA Javascript
Hint

Use recursion to check if the target is found. Return true if found, false if you reach a null node.

4
Print the search result
Use console.log to print Found if searchBST(root, target) returns true, otherwise print Not Found.
DSA Javascript
Hint

Call searchBST with root and target. Print "Found" if true, else "Not Found".