You are on page 1of 3

C++ code to implement searching in binary search tree:

#include <iostream>

struct TreeNode {
int key;
TreeNode* left;
TreeNode* right;

TreeNode(int k) : key(k), left(nullptr), right(nullptr) {}


};

class BinarySearchTree {
private:
TreeNode* root;

// Recursive helper function for searching in BST


TreeNode* searchHelper(TreeNode* node, int key) {
if (node == nullptr || node->key == key)
return node;

if (key < node->key)


return searchHelper(node->left, key);
else
return searchHelper(node->right, key);
}

public:
BinarySearchTree() : root(nullptr) {}

// Function to insert a key into the BST


void insert(int key) {
if (root == nullptr) {
root = new TreeNode(key);
return;
}

TreeNode* current = root;


TreeNode* parent = nullptr;

while (current != nullptr) {


parent = current;
if (key < current->key)
current = current->left;
else
current = current->right;
}

if (key < parent->key)


parent->left = new TreeNode(key);
else
parent->right = new TreeNode(key);
}

// Function to search for a key in the BST


bool search(int key) {
TreeNode* result = searchHelper(root, key);
return (result != nullptr);
}
};

int main() {
BinarySearchTree bst;

// Insert elements into the BST


bst.insert(50);
bst.insert(30);
bst.insert(70);
bst.insert(20);
bst.insert(40);
bst.insert(60);
bst.insert(80);

// Search for keys in the BST


std::cout << "Search for 40: " << (bst.search(40) ? "Found" : "Not Found") << std::endl;
std::cout << "Search for 90: " << (bst.search(90) ? "Found" : "Not Found") << std::endl;

return 0;
}

You might also like