As it is said in the title I am trying to create a code which converts a postfix notation to an expression tree. Here you can check the constructor :
public byte type; // 0 : operator, 1: operand (a number)
public char operator; // One of '+', '-', '*', '/'
public int operand; // A number
ExpressionTreeNode(byte type){this.type = type; left=right=null;}
and Here is my code :
public static ExpressionTreeNode Postfix2ExpressionTree(String postfixExpr){
Stack s = new Stack<Object>();
ExpressionTreeNode root = new ExpressionTreeNode((byte) 0);
root.operator = postfixExpr.charAt(postfixExpr.length()-1);
String number = "";
for(int i = 0;i<postfixExpr.length()-1;i++){
if(Character.isDigit(postfixExpr.charAt(i)) == true){
number = number + postfixExpr.charAt(i);
if(Character.isDigit(postfixExpr.charAt(i+1)) == false){
ExpressionTreeNode node = new ExpressionTreeNode((byte) 1);
node.operand = Integer.valueOf(number);
node.right = null;
node.left = null;
s.push(node);
number = "";
}
}
if(i == postfixExpr.length()-2){
root.right = (ExpressionTreeNode) s.pop();
root.left =(ExpressionTreeNode) s.pop();
s.push(root);
break;
}
else {
if(postfixExpr.charAt(i) == '+' || postfixExpr.charAt(i) == '*' || postfixExpr.charAt(i) == '-' || postfixExpr.charAt(i) == '/' ){
ExpressionTreeNode node = new ExpressionTreeNode((byte)0);
node.operand = postfixExpr.charAt(i);
node.right = (ExpressionTreeNode) s.pop();
node.left = (ExpressionTreeNode) s.pop();
s.push(node);
}
}
}
return (ExpressionTreeNode) s.pop();
}
I check every character one by one with charAt() method. Simply 1-push every operand into the stack 2-when operator is encountered pop two operand from the stack and assign them to right and left of operator then push the new node to the stack. 3- and finally I push the root to the stack then return it.
No error occurs when I try to run but also it is not working in the right way too. I checked the code many times but I couldn't solve it.If anyone sees the mistake and help me , that would be great.