Practical No.
2
Q. Beginning with an empty binary search tree, Construct binary search tree by
inserting the values in the order given. After constructing a binary tree –
i. Insert new node
ii. Find number of nodes in longest path
iii. Minimum data value found in the tree
iv. Change a tree so that the roles of the left and right pointers are swapped at
every node
v. Search a value.
Ans:-
#include <iostream>
#include <algorithm>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = nullptr;
};
Node* insert(Node* root, int data) {
if (root == nullptr)
return new Node(data);
if (data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
int longestPath(Node* root) {
if (root == nullptr)
return 0;
return 1 + max(longestPath(root->left), longestPath(root->right));
int findMin(Node* root) {
if (root == nullptr) {
cout << "Tree is empty.\n";
return -1;
Node* current = root;
while (current->left != nullptr)
current = current->left;
return current->data;
void mirrorTree(Node* root) {
if (root == nullptr)
return;
mirrorTree(root->left);
mirrorTree(root->right);
Node* temp = root->left;
root->left = root->right;
root->right = temp;
bool search(Node* root, int key) {
if (root == nullptr)
return false;
if (root->data == key)
return true;
else if (key < root->data)
return search(root->left, key);
else
return search(root->right, key);
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
int main() {
Node* root = nullptr;
int values[] = {50, 30, 20, 40, 70, 60, 80};
for (int val : values)
root = insert(root, val);
cout << "Inorder traversal of initial BST: ";
inorder(root);
cout << endl;
int newNode = 25;
root = insert(root, newNode);
cout << "After inserting " << newNode << ", Inorder: ";
inorder(root);
cout << endl;
cout << "Height of tree (longest path): " << longestPath(root) << endl;
cout << "Minimum value in BST: " << findMin(root) << endl;
mirrorTree(root);
cout << "Inorder traversal after mirroring: ";
inorder(root);
cout << endl;
int key = 60;
cout << "Search " << key << ": " << (search(root, key) ? "Found" : "Not Found") << endl;
return 0;
Output:-