#include <iostream>
#include <string>
#include <stack>
#include "BinaryTree.cpp"
using namespace std;
void createTree(const string & postfix);
void toPostFix(const string & infix, string & postfix);
bool isOperand(char ch);
bool hasPrecedence(char OperatorA, char OperatorB);
int main(void) {
string infix, postfix; // local to this loop
cout << endl << endl << "Enter an infix expression: ";
cin >> infix;
toPostFix(infix, postfix);
cout << endl << "The equivalent postfix expression is: " << postfix << endl << endl;
createTree(postfix);
cout << endl << endl << endl;
return 0;
}
bool isOperand(char ch)
{
if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) || ((ch >= '0') && (ch <= '9')))
return true;
else return false;
}
bool hasPrecedence(char OperatorA, char OperatorB)
{
if (OperatorA == '(') return false;
else if (OperatorB == '(') return false;
else if (OperatorB == ')') return true;
else if ((OperatorA == '^') && (OperatorB == '^')) return false;
else if (OperatorA == '^') return true;
else if (OperatorB == '^') return false;
else if ((OperatorA == '*') || (OperatorA == '/')) return true;
else if ((OperatorB == '*') || (OperatorB == '/')) return false;
else
return true;
}
void toPostFix(const string & infix, string & postfix)
{
stack<char> OperatorStack;
char TopSymbol, Symbol;
int k;
for (k = 0; k < infix.size(); k++)
{
Symbol = infix[k];
if (isOperand(Symbol))
postfix = postfix + Symbol;
else {
while ((! OperatorStack.empty()) && (hasPrecedence(OperatorStack.top(), Symbol))) {
TopSymbol = OperatorStack.top();
OperatorStack.pop();
postfix = postfix + TopSymbol;
}
if ((! OperatorStack.empty()) && (Symbol == ')'))
OperatorStack.pop(); // discard matching (
else
OperatorStack.push(Symbol);
}
}
while (! OperatorStack.empty())
{
TopSymbol = OperatorStack.top();
OperatorStack.pop();
postfix = postfix + TopSymbol;
}
}
void createTree(const string & postfix) {
stack<Tree> s;
for (int i=0; i<postfix.length(); i++) {
if (isOperand(postfix[i])) {
Tree *t;
t=new Tree(postfix[i],NULL,NULL);
s.push(*t);
}
else {
Tree *tc;
Tree ta=s.top();
s.pop();
Tree tb=s.top();
s.pop();
tc = new Tree(postfix[i],&tb,&ta);
s.push(*tc);
}
}
Tree *mytree;
mytree = &s.top();
s.pop();
cout << " Tree is " << mytree->RootData() << " with left " << mytree->Left()->RootData() << " and right " << mytree->Right()->RootData() << endl;
(mytree->Right()->Left() == NULL) ? cout << endl : cout << mytree->Right()->Left()->RootData() << endl;
(mytree->Right()->Right() == NULL) ? cout << endl : cout << mytree->Right()->Right()->RootData() << endl;
cout << " Tree is " << mytree->Left()->RootData() << " with left " << mytree->Left()->Left()->RootData() << " and right " << mytree->Left()->Right()->RootData() << endl;
//mytree->preorder(mytree);
return;
}