Skip to main content

Binary Tree | Inorder, Preorder, Postorder Recursive and Non-Recursive Traversal | Mirror Binary Tree | Height of Tree | Cloning Binary Tree | Number of Leaves | Number of Internal Nodes | Erasing all nodes of Binary Tree

 Problem Statement: Beginning with an empty binary tree, construct a binary tree by inserting the values in the order given. After constructing a binary tree perform the following operations on it-

  • Perform inorder, preorder and postorder traversal (Implement both recursive and non-recursive methods)
  • Change a tree so that the roles of the left and right pointers are swapped at every node
  • Find the height of the tree
  • Copy this tree to another 
  • Count number of leaves, number of internal nodes.
  • Erase all nodes in a binary tree
Note:- Scroll horizontally to see the full line of code.

#include <iostream>
using namespace std;

class node
{
    // data members
public:
    int data;
    node *left;
    node *right;

    // node constructor
    node(int val)
    {
        data = val;
    }
};

class nodePointer
{
public:
    node *link;
    int flag = 0;
};

class nodeStack
{
    nodePointer *nodes;
    int top;

public:
    nodeStack()
    {
        nodes = new nodePointer[30];
        top = -1;
    }

    void push(node *x, int n = 0)
    {
        if (!full())
        {
            top++;
            nodes[top].link = x;
            nodes[top].flag = n;
        }
    }
    node *Top()
    {
        if (!isEmpty())
        {
            return nodes[top].link;
        }
        else
        {
            return NULL;
        }
    }
    int TopFlag()
    {
        if (!isEmpty())
        {
            return nodes[top].flag;
        }
        else
        {
            return -1;
        }
    }
    void pop()
    {
        if (!isEmpty())
        {
            top--;
        }
        else
        {
            cout << "Stack is already empty!";
        }
    }
    bool full()
    {
        if (top == 29)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    bool isEmpty()
    {
        if (top == -1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

node *createBinaryTree()
{
    node *root;
    cout << "Enter Data: ";
    int val;
    cin >> val;

    if (val == -1)
    {
        return NULL;
    }
    root = new node(val);

    cout << "Enter left for " << val << " :" << endl;
    root->left = createBinaryTree();

    cout << "Enter right for " << val << " :" << endl;
    root->right = createBinaryTree();

    return root;
}

void preorder(node *root)
{
    if (root)
    {
        cout << root->data << " ";
        preorder(root->left);
        preorder(root->right);
    }
}

void preorderNonRecursive(node *root)
{
    nodeStack Pointers;
    if (root)
    {
        node *current = root;
        while (current || !Pointers.isEmpty())
        {
            if (!current && !Pointers.isEmpty())
            {
                current = Pointers.Top();
                Pointers.pop();
                current = current->right;
            }
            else
            {
                cout << current->data << " ";
                Pointers.push(current);
                current = current->left;
            }
        }
    }
}

void postorder(node *root)
{
    if (root)
    {
        postorder(root->left);
        postorder(root->right);
        cout << root->data << " ";
    }
}

void postorderNonRecursive(node *root)
{
    nodeStack Pointers;
    node *current = root;
    while (current || !Pointers.isEmpty())
    {
        if (!current && !Pointers.isEmpty())
        {
            current = Pointers.Top();

            if (Pointers.TopFlag() == 0)
            {
                Pointers.pop();
                Pointers.push(current, 1);
                current = current->right;
            }
            else if (Pointers.TopFlag() == 1)
            {
                cout << current->data << " ";
                Pointers.pop();
                current = NULL;
            }
        }
        else
        {
            Pointers.push(current, 0);
            current = current->left;
        }
    }
}

void inorder(node *root)
{
    if (root)
    {
        inorder(root->left);
        cout << root->data << " ";
        inorder(root->right);
    }
}

void inorderNonRecursive(node *root)
{
    nodeStack Pointers;
    if (root)
    {
        node *current = root;
        while (current != NULL || !Pointers.isEmpty())
        {

            if (current == NULL && !Pointers.isEmpty())
            {
                current = Pointers.Top();
                Pointers.pop();
                cout << current->data << " ";
                current = current->right;
            }
            else
            {
                Pointers.push(current);
                current = current->left;
            }
        }
    }
    else
    {
        cout << "Tree is empty" << endl;
    }
}

int btHeight(node *root)
{
    if (!root)
    {
        return -1;
    }
    else
    {
        int leftBTHeight = btHeight(root->left);
        int rightBTHeight = btHeight(root->right);
        return (leftBTHeight > rightBTHeight ? leftBTHeight : rightBTHeight) + 1;
    }
}

node *swapBT(node *root)
{
    if (!root)
    {
        return NULL;
    }
    else
    {
        root->left = swapBT(root->left);
        root->right = swapBT(root->right);
        node *temp = root->left;
        root->left = root->right;
        root->right = temp;
        return root;
    }
}

int leafNodes(node *root)
{
    if (!root)
    {
        return 0;
    }
    if (root->left == NULL && root->right == NULL)
    {
        return 1;
    }
    else
        return (leafNodes(root->left) + leafNodes(root->right));
}

int internalNode(node *root)
{
    if (!root || (!root->left && !root->right))
    {
        return 0;
    }
    else
        return (1 + (internalNode(root->left) + internalNode(root->right)));
}

void deleteTree(node *root)
{
    if (!root)
    {
        return;
    }
    deleteTree(root->left);
    deleteTree(root->right);
    cout << "Deleting node: " << root->data << endl;
    delete root;
}

node *cloneBinaryTree(node *root)
{
    if (root == NULL)
    {
        return NULL;
    }

    node *root_copy = new node(root->data);
    root_copy->left = cloneBinaryTree(root->left);
    root_copy->right = cloneBinaryTree(root->right);

    return root_copy;
}

int main()
{
    node *root;

    char cont = 'y';
    while (cont == 'y')
    {

        int choice;
        cout << "<----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.Leaf Node" << endl;
        cout << "6.Internal Nodes" << endl;
        cout << "7.Height of Tree" << endl;
        cout << "8.Clone Tree" << endl;
        cout << "9.Swap Nodes" << endl;
        cout << "10.Delete Tree" << endl;
        cout << "Enter the Choice: ";
        cin >> choice;
        switch (choice)
        {
        case 1:
            root = createBinaryTree();
            cout << "Tree Created Successfully" << endl;
            break;
        case 2:
            int choice1;
            cout << "1. Recursive Inorder" << endl;
            cout << "2. Non Recursive Inorder" << endl;
            cout << "Enter the choice: ";
            cin >> choice1;
            switch (choice1)
            {
            case 1:
                cout << "Inorder Traversal: ";
                inorder(root);
                cout << endl;
                break;
            case 2:
                cout << "Inorder NonRecursive: ";
                inorderNonRecursive(root);
                cout << endl;
                break;
            default:
                cout << "INVALID CHOICE." << endl;
                break;
            }
            break;
        case 3:
            int choice2;
            cout << "1. Recursive Preorder" << endl;
            cout << "2. Non Recursive Preorder" << endl;
            cout << "Enter the choice: ";
            cin >> choice2;
            switch (choice2)
            {
            case 1:
                cout << "Preorder Traversal: ";
                preorder(root);
                cout << endl;
                break;
            case 2:
                cout << "Preorder NonRecursive: ";
                preorderNonRecursive(root);
                cout << endl;
                break;
            default:
                cout << "INVALID CHOICE." << endl;
                break;
            }
            break;
        case 4:
            int choice3;
            cout << "1. Recursive Postorder" << endl;
            cout << "2. Non Recursive Postorder" << endl;
            cout << "Enter the choice: ";
            cin >> choice3;
            switch (choice3)
            {
            case 1:
                cout << "Postorder Traversal: ";
                postorder(root);
                cout << endl;
                break;
            case 2:
                cout << "Inorder NonRecursive: ";
                postorderNonRecursive(root);
                cout << endl;
                break;
            default:
                cout << "INVALID CHOICE." << endl;
                break;
            }
            break;
        case 5:
            cout << "No. of Leaf Nodes: " << leafNodes(root) << endl;
            break;
        case 6:
            cout << "No. of Internal Nodes: " << internalNode(root) << endl;
            break;
        case 7:
            cout << "Height of Tree: " << btHeight(root) << endl;
            break;
        case 8:
            node *clonetree;
            clonetree = cloneBinaryTree(root);
            cout << "Tree copied Successfully" << endl;
            cout << "Inorder Traversal of Clone Tree: ";
            inorder(clonetree);
            cout << endl;
            break;
        case 9:
            root = swapBT(root);
            cout << "Inorder Traversal after mirroring: ";
            inorder(root);
            cout << endl;
            break;
        case 10:
            deleteTree(root);
            cout << "Tree Deleted Successfully!" << endl;
            break;
        default:
            cout << "INVALID CHOICE!!!" << endl;
            break;
        }
        cout << "Do yo want to continue? (y/n): ";
        cin >> cont;
    }

    cout << "Program Ended Successfully!!!" << endl;
    return 0;
}

Comments

Popular posts from this blog

SET THEORY USING LIST IN PYTHON

Problem Statement :- In second-year computer engineering class, group A student's play cricket, group B students play badminton and group C students play football.  Write a Python program using functions to compute the following:-     a) List of students who play both cricket and badminton     b) List of students who play either cricket or badminton or both     c) Number of students who play neither cricket nor badminton     d) Number of students who play cricket and football but not badminton. (Note- While realizing the group, duplicate entries should be avoided, Do not use SET built-in functions) Note :- Scroll horizontally to see the full line of code. def   Addelem ( A ,  a ):      for   i   in   range  ( a ):          elem = input ( "Enter the name of student:" )          if ( elem   ...

Uninstalling AnyDesk from Ubuntu: A Step-by-Step Guide

If you're an Ubuntu user looking to remove AnyDesk from your system and reclaim valuable space, this straightforward guide will walk you through the uninstallation process with easy-to-follow steps. Step 1: Launch the Terminal To initiate the uninstallation process, open the Terminal on your Ubuntu system by simultaneously pressing "Ctrl + Alt + T." Step 2: Verify AnyDesk Installation Confirm that AnyDesk is installed on your system by typing the following command in the Terminal and pressing "Enter": dpkg -l | grep anydesk The relevant information will be displayed if AnyDesk is installed. Step 3: Uninstall AnyDesk Remove AnyDesk from your Ubuntu system using the following command in the Terminal: sudo apt-get remove anydesk Enter your user password when prompted (characters won't be visible as you type) and press "Enter" to authorize the uninstallation. Step 4: Confirm Unins...

Implementations of Search Algorithms using Python | Linear Sequential Search | Sentinel Sequential Search | Binary Search | Fibonacci Search

  Problem Statement:-  a) Write a Python program to store roll numbers of student in array who attended training program in random order. Write function for searching whether particular student attended training program or not, using Linear search and Sentinel search. b) Write a Python program to store roll numbers of students array who attended training program in sorted order. Write function for searching whether particular student attended training program or not, using Binary search and Fibonacci search. Note:-  Scroll horizontally to see the full line of code. def linear_search ( a , target ):     for i in range ( len ( a )):         if ( a [ i ]== target ):             print ( "Roll no." , target , "is present at index" , i )             break     else :         print ( "Roll no." , target , "not found in list" ) def binary_search ( a , targ...

C++ Program for storing Appointments Schedule for day using Linked list | Display Free Slots | Book Appointment | Cancel Appointment | Sort Appointments

  Problem Statement: Write C++ program for storing appointment schedule for day. Appointments are booked randomly using linked list. Set start and end time and min and max duration for visit slot. Write Functions for-     A) Display free slots     B) Book appointments     C) Sort list based on time     D) Cancel appointment ( check validity, time bounds, availability )     E) Sort list base on time using pointer manipulation. Note: Scroll Horizontally to see the full line of code. #include < iostream > using namespace std ; class slot { public :     int startTime , endTime , min , max ;     bool status ;     slot * next ;     slot ( int start , int end , int min , int max )     {         startTime = start ;         endTime = end ;         this -> min = min ;         this ->...

Complete Guide: Uninstalling Steam from Ubuntu - Step-by-Step

Steam is widely favored among gamers for its seamless game distribution and vibrant community engagement. However, excessive game installations can burden your PC, leading to sluggish performance and potential system crashes. If you're facing such issues, a thorough uninstallation of Steam from your Ubuntu system might be the solution. Simply removing Steam using standard methods may leave residual files and directories on your device, potentially causing lingering issues. This comprehensive guide will walk you through the process of completely removing Steam from your Ubuntu system. Steps to Fully Uninstall Steam from Ubuntu: Before proceeding, ensure to back up any important data as uninstalling Steam will also remove all associated games, DLCs, and saved data. Follow these steps to uninstall Steam from Ubuntu: Step 1: Open the terminal by right-clicking or pressing “ctrl...