0
0
DSA C++programming~30 mins

BST Search Operation in DSA C++ - Build from Scratch

Choose your learning style9 modes available
BST Search Operation
📖 Scenario: You are working with a phone book application that stores contacts in a Binary Search Tree (BST). Each contact has a unique phone number. You want to find if a particular phone number exists in the phone book.
🎯 Goal: Build a simple BST and write code to search for a given phone number in it.
📋 What You'll Learn
Create a BST node structure with integer phone numbers
Manually create a BST with given phone numbers
Write a function to search for a phone number in the BST
Print whether the phone number is found or not
💡 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 fundamental for software engineers working with data storage, retrieval, and optimization.
Progress0 / 4 steps
1
Create BST Node Structure and Root Node
Create a struct called Node with an int data, and two pointers left and right of type Node*. Then create a Node* variable called root and initialize it with a new node containing the value 50.
DSA C++
Hint

Think of a tree node as a box holding a number and two pointers to other boxes.

2
Add Left and Right Child Nodes to Root
Add two child nodes to root: set root->left to a new node with value 30 and root->right to a new node with value 70. Both children should have their left and right pointers set to nullptr.
DSA C++
Hint

Attach smaller number to the left and bigger number to the right of root.

3
Write a Function to Search for a Value in BST
Write a function called searchBST that takes a Node* called root and an int key. It should return true if key is found in the BST, otherwise false. Use the BST property to decide whether to search left or right.
DSA C++
Hint

Check if current node is null or matches key. If not, go left if key is smaller, else right.

4
Search for a Phone Number and Print Result
Call searchBST with root and the key 70. Print "Found" if the function returns true, otherwise print "Not Found".
DSA C++
Hint

Use an if statement to print "Found" if searchBST returns true, else "Not Found".