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

Practical No. - 4 - B

Uploaded by

nikita.khawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

Practical No. - 4 - B

Uploaded by

nikita.khawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

#include <iostream>

using namespace std;

// Node structure

struct Node {

int data;

Node* left;

Node* right;

Node(int value) : data(value), left(nullptr), right(nullptr) {}

};

class BST {

public:

Node* root;

BST() : root(nullptr) {}

// Insert a node into the BST

Node* insert(Node* node, int value) {

if (node == nullptr) {

return new Node(value);

if (value < node->data) {

node->left = insert(node->left, value);

} else {

node->right = insert(node->right, value);

return node;
}

// Find the height of the tree

int findHeight(Node* node) {

if (node == nullptr) {

return 0;

int leftHeight = findHeight(node->left);

int rightHeight = findHeight(node->right);

return max(leftHeight, rightHeight) + 1;

// Find the minimum value in the BST

int findMin(Node* node) {

Node* current = node;

while (current && current->left != nullptr) {

current = current->left;

return current->data;

// Swap the left and right pointers of every node

void mirror(Node* node) {

if (node == nullptr) {

return;

swap(node->left, node->right);

mirror(node->left);

mirror(node->right);
}

// Search for a value in the BST

bool search(Node* node, int value) {

if (node == nullptr) {

return false;

if (node->data == value) {

return true;

return value < node->data ? search(node->left, value) : search(node->right, value);

};

int main() {

BST tree;

// Construct BST by inserting values

tree.root = tree.insert(tree.root, 8);

tree.insert(tree.root, 3);

tree.insert(tree.root, 10);

tree.insert(tree.root, 1);

tree.insert(tree.root, 6);

tree.insert(tree.root, 14);

tree.insert(tree.root, 4);

tree.insert(tree.root, 7);

tree.insert(tree.root, 13);

// i. Insert new node

tree.insert(tree.root, 2);
// ii. Find number of nodes in longest path from root

cout << "Height of tree: " << tree.findHeight(tree.root) - 1 << endl; // Subtracting 1 to get the number
of edges

// iii. Minimum data value found in the tree

cout << "Minimum value in tree: " << tree.findMin(tree.root) << endl;

// iv. Change a tree so that the roles of the left and right pointers are swapped at every node

tree.mirror(tree.root);

cout << "Tree mirrored." << endl;

// v. Search a value

int searchValue = 7;

cout << "Value " << searchValue << (tree.search(tree.root, searchValue) ? " found" : " not found") << "
in the tree." << endl;

return 0;

You might also like