Create Binary Search Tree(BST).Find height of the tree and print leaf nodes. Find mirror image, print original and mirror image using level-wise printing.
CODE:
#include <iostream>
#include <queue>
using namespace std;
// Define the structure for a tree node
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
};
// Function to create a new node
TreeNode* createNode(int value) {
TreeNode* newNode = new TreeNode();
newNode->data = value;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
// Function to insert a node into the BST
TreeNode* insert(TreeNode* root, int value) {
if (root == nullptr) {
return createNode(value);
}
if (value < root->data) {
root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}
return root;
}
// Function to find the height of the tree
int height(TreeNode* root) {
if (root == nullptr) {
return -1;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + max(leftHeight, rightHeight);
}
// Function to print leaf nodes
void printLeafNodes(TreeNode* root) {
if (root == nullptr) {
return;
}
if (root->left == nullptr && root->right == nullptr) {
cout << root->data << " ";
}
printLeafNodes(root->left);
printLeafNodes(root->right);
}
// Function to swap left and right children of a tree
void mirror(TreeNode* root) {
if (root == nullptr) {
return;
}
mirror(root->left);
mirror(root->right);
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
}
// Function to print the tree level-wise
void printLevelOrder(TreeNode* root) {
if (root == nullptr)
return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int nodeCount = q.size();
while (nodeCount > 0) {
TreeNode* node = q.front();
q.pop();
cout << node->data << " ";
if (node->left != nullptr)
q.push(node->left);
if (node->right != nullptr)
q.push(node->right);
nodeCount--;
}
cout << endl;
}
}
int main() {
TreeNode* root = nullptr;
int n;
cout << "Enter the number of nodes in the BST: ";
cin >> n;
cout << "Enter the values of nodes: ";
for (int i = 0; i < n; ++i) {
int value;
cin >> value;
root = insert(root, value);
}
cout << "Height of the BST: " << height(root) << endl;
cout << "Leaf nodes: ";
printLeafNodes(root);
cout << endl;
cout << "Original Tree:" << endl;
printLevelOrder(root);
mirror(root);
cout << "Mirror Image:" << endl;
printLevelOrder(root);
return 0;
}