Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Node {
- public:
- int data;
- Node *left;
- Node *right;
- };
- class BST {
- private:
- Node *root;
- public:
- BST() {
- root = nullptr;
- }
- void createTree() {
- Node *temp, *curr;
- do {
- temp = new Node;
- cout << "Enter data: "; cin >> temp->data;
- temp->left = temp->right = nullptr;
- if (root == nullptr) {
- root = temp;
- } else {
- curr = root;
- while (1) {
- // Left
- if (temp->data < curr->data) {
- if (curr->left == nullptr) {
- curr->left = temp;
- break;
- } else {
- curr = curr->left;
- }
- }
- // Right
- if (temp->data >= curr->data) {
- if (curr->right == nullptr) {
- curr->right = temp;
- break;
- } else {
- curr = curr->right;
- }
- }
- }
- }
- int flag;
- cout << "Want to enter a new node? (0 for NO): "; cin >> flag;
- if (flag == 0) break;
- } while (true);
- }
- void preorder(Node *root) {
- if (root == nullptr) return;
- cout << root->data << "\t";
- preorder(root->left);
- preorder(root->right);
- }
- void postorder(Node *root) {
- if (root == nullptr) return;
- preorder(root->left);
- preorder(root->right);
- cout << root->data << "\t";
- }
- void inorder(Node *root) {
- if (root == nullptr) return;
- preorder(root->left);
- cout << root->data << "\t";
- preorder(root->right);
- }
- void displayTree() {
- if (root == nullptr) {
- cout << "Tree empty" << endl;
- } else {
- cout << "Display" << endl;
- int choice;
- cout << "1. Postorder" << endl;
- cout << "2. Inorder" << endl;
- cout << "3. Preorder" << endl;
- cout << "4. All" << endl;
- cout << "Enter choice: " << endl; cin >> choice;
- if (choice == 1) {
- cout << "Postorder Traversal: " << endl;
- postorder(root);
- cout << endl;
- } else if (choice == 2) {
- cout << "Inorder Traversal: " << endl;
- inorder(root);
- cout << endl;
- } else if (choice == 3) {
- cout << "Preorder Traversal: " << endl;
- preorder(root);
- cout << endl;
- } else if (choice == 4) {
- cout << "Postorder Traversal: " << endl;
- postorder(root);
- cout << endl;
- cout << "Inorder Traversal: " << endl;
- inorder(root);
- cout << endl;
- cout << "Preorder Traversal: " << endl;
- preorder(root);
- cout << endl;
- } else {
- cout << "Invalid Input" << endl;
- }
- }
- }
- };
- int main() {
- BST Tree;
- Tree.createTree();
- Tree.displayTree();
- cout << "\nEnding program" << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment