Binary Tree
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
// Function to create a new node
Node* createNode(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
// Function to insert a node in the binary tree
Node* insertNode(Node* root, int value) {
if (root == nullptr) {
root = createNode(value);
} else if (value < root->data) {
root->left = insertNode(root->left, value);
} else {
root->right = insertNode(root->right, value);
}
return root;
}
// Inorder Traversal (Left, Root, Right)
void inorderTraversal(Node* root) {
if (root == nullptr) return;
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
// Preorder Traversal (Root, Left, Right)
void preorderTraversal(Node* root) {
if (root == nullptr) return;
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// Postorder Traversal (Left, Right, Root)
void postorderTraversal(Node* root) {
if (root == nullptr) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->data << " ";
}
// Function to create the binary tree with given values
Node* createBinaryTree() {
Node* root = nullptr;
int values[] = {8, 10, 3, 1, 6, 14, 7};
for (int i = 0; i < 7; i++) {
root = insertNode(root, values[i]);
}
return root;
}
int main() {
Node* root = nullptr;
int choice;
while (true) {
cout << "\n--- Binary Tree Menu ---" << endl;
cout << "1. Create Binary Tree" << endl;
cout << "2. Inorder Traversal" << endl;
cout << "3. Preorder Traversal" << endl;
cout << "4. Postorder Traversal" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
root = createBinaryTree();
cout << "Binary Tree created successfully!" << endl;
break;
case 2:
cout << "Inorder Traversal: ";
inorderTraversal(root);
cout << endl;
break;
case 3:
cout << "Preorder Traversal: ";
preorderTraversal(root);
cout << endl;
break;
case 4:
cout << "Postorder Traversal: ";
postorderTraversal(root);
cout << endl;
break;
case 5:
cout << "Exiting program." << endl;
return 0;
default:
cout << "Invalid choice! Please try again." << endl;
}
}
return 0;
}
Comments
Post a Comment