I have a binary tree containing integers in the external nodes and operators in the internal nodes.
I send the root node of the tree to my evaluateTree method.
I want to traverse the tree and to calculate the final result.
The node class's fields are
private Node left;
private Node right;
char value;
For example, I want to evaluate (2+5)/8-(21+3) should equal, with rounding, to -23.
When I try to do so, I get a result of -5. Unrelated to rounding, when I try to calculate 21+3, i get a result of 5. Any guidance would be appreciated.
int evaluateTree(Node node)
{
System.out.println("Inside evaluateTree");
if (Character.isDigit(node.value))
{
return Character.getNumericValue(node.value);
}
else
{
int operand1 = evaluateTree(node.left);
int operand2 = evaluateTree(node.right);
switch (node.value)
{
case '+':
return (int) Math.round(operand1 + operand2);
case '-':
return (int) Math.round(operand1 - operand2);
case '*':
return (int) Math.round(operand1 * operand2);
case '/':
return (int) Math.round(operand1 / operand2);
default:
throw new IllegalStateException("Unexpected value: " + node.value);
}
}
}
This is how i create my tree
public void createTree()
{
Scanner keyboardInput = new Scanner(System.in);
ArrayList<String> postFixArray = new ArrayList<>();
postFixArray = getPostFixString("(21+3)");
System.out.println("\nCREATE TREE PRINTING\n");
System.out.println(postFixArray);
Stack<Node> nodeStack = new Stack<>();
while (!postFixArray.isEmpty())
{
String temp = postFixArray.get(0);
char charTemp = temp.charAt(0);
if (!isOperator(charTemp))
{
if (!Character.isDigit(charTemp))
{
System.out.println("Enter the integer value for your variable " + charTemp + ": ");
int setVarValue = keyboardInput.nextInt();
for (int i = 0; i < postFixArray.size(); i++)
{
if (charTemp == postFixArray.get(i).charAt(0))
{
postFixArray.set(i, String.valueOf(setVarValue));
}
}
}
String tempLink = postFixArray.remove(0);
char nodeData = tempLink.charAt(0);
Node leaf = new Node(nodeData);
nodeStack.push(leaf);
}
else
{
if (nodeStack.size() >= 1)
{
String tempLink = postFixArray.remove(0);
char nodeData = tempLink.charAt(0);
Node leaf = new Node(nodeData);
leaf.right = nodeStack.pop();
leaf.left = nodeStack.pop();
nodeStack.push(leaf);
}
}
}
Node root = nodeStack.pop();
System.out.println(root);
System.out.println(evaluateTree(root));
}