0% found this document useful (0 votes)
8 views4 pages

Binary Search Tree

The document provides a C++ implementation of a Binary Search Tree (BST) including functions for node creation, insertion, searching, and inorder traversal. It demonstrates the insertion of several integers into the BST and performs an inorder traversal to display the values. Additionally, it includes a search function to check for the presence of a specific key in the tree.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Binary Search Tree

The document provides a C++ implementation of a Binary Search Tree (BST) including functions for node creation, insertion, searching, and inorder traversal. It demonstrates the insertion of several integers into the BST and performs an inorder traversal to display the values. Additionally, it includes a search function to check for the presence of a specific key in the tree.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

PROGRAM

BINARY SEARCH TREE


LANGUAGE – C++
```
#include <iostream>
using namespace std;

struct Node {
int data;
Node *left;
Node *right;
};

Node* newNode(int key) {


Node* node = new Node();
node->data = key;
node->left = node->right = NULL;
return node;
}

Node* insert(Node* root, int key) {


if (root == NULL) {
return newNode(key);
}
if (key < root->data) {
root->left = insert(root->left, key);
}
else if (key > root->data) {
root->right = insert(root->right, key);
}
return root;
}

Node* search(Node* root, int key) {


if (root == NULL || root->data == key) {
return root;
}
if (key < root->data) {
return search(root->left, key);
}
else {
return search(root->right, key);
}
}

void inorder(Node* root) {


if (root != NULL) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}

int main() {
Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

cout << "Inorder traversal of the BST is: ";


inorder(root);

int key = 60;


Node* result = search(root, key);
if (result == NULL) {
cout << "\nKey not found in the BST.\n";
}
else {
cout << "\nKey found in the BST.\n";
}

return 0;
}
```

You might also like