Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Wednesday, February 4, 2015

Fully Parenthesized Infix Expression From Postfix Expression

The problem is that you are given a post fix expression and you need to convert it to a fully parenthesize infix expression.

Exmple:
  • Input: ab+
  • Output: (a+b)
The approach used in this program is to print the parenthesis durin infix traversal of the expression tree built from the postfix expression.
#include <iostream>
#include <stack>

using namespace std;

typedef struct Node
{
    char data;
    Node *lChild, *rChild;
}Node;

class ExpressionTree
{
    private:
        Node *root;
    public:
        ExpressionTree() { root = NULL; }
        ExpressionTree(char[]);
        Node* getRoot() { return root; }
        Node* createNode(char , Node*, Node*);
        friend bool isOperator(char);
        friend void inOrder();
};

bool isOperator(char opp)
{
    switch(opp)
    {
        case '+':
        case '*':
        case '/':
        case '^':
        case '-':
            return true;
        default:
            return false;
    }
}

Node* ExpressionTree::createNode(char ch, Node *l, Node *r)
{
    Node *tmp = new Node();
    tmp->data = ch;
    tmp->lChild = l;
    tmp->rChild = r;
    return tmp;
}

ExpressionTree::ExpressionTree(char arr[])
{
    stack<Node*> s;
    Node *ptr, *l, *r;
    int i = 0;
    while(arr[i])
    {
        if(isOperator(arr[i]))
        {
            l = s.top();
            s.pop();
            r = s.top();
            s.pop();
            ptr = createNode(arr[i], r , l);
        }
        else
        {
            ptr = createNode(arr[i], NULL, NULL);
        }
        s.push(ptr);
        i++;
    }
    root = s.top();
}


void inOrder(Node* T)
{
    if(T != NULL)
    {
        if(isOperator(T->data)) cout << "(";

        inOrder(T->lChild);
        cout << T->data;
        inOrder(T->rChild);

        if(isOperator(T->data)) cout << ")";
    }
}

int main()
{
    char exp[50];
    
    cout << "Enter A Postfix Expression:" << ends;
    cin >> exp;
    
    ExpressionTree t(exp);
    
    cout << "Given Postfix Expression:" << ends;
    cout << exp << endl;
    
    cout << "In-order Form: " << ends;
    inOrder(t.getRoot());
    
    return 0;
}
Enter A Postfix Expression: ab+c*
Given Postfix Expression: ab+c*
In-order Form:  ((a+b)*c)
--------------------------------
Process exited after 6.555 seconds with return value 0
Press any key to continue . . .