I've seen approaches on how to iterate through binary trees and find the sum of all nodes, except I'm evaluating expression inputs for a calculator. The nodes are arranged in the proper order according to order of operations and the nodes are either operators
or operands
. I think recursion
is slower than iteration for this so I wanted to figure out how to go through the binary tree and find the result of the expression inputed without recursion
.
An example of the tree:
+
* /
3 4 4 2
The recursive method I have so far (I used an enum for the operator):
public static float evaluate(BETNode root)
{
if (root == null)
{
throw new IllegalArgumentException("Error: Root is null!");
}
if (root.getType() == BETNodeType.OPERAND)
{
return root.getOperand();
}
float leftValue = evaluate(root.getLeft());
float rightValue = evaluate(root.getRight());
switch (root.getOperator())
{
case '+':
return leftValue + rightValue;
case '-':
return leftValue - rightValue;
case '*':
return leftValue * rightValue;
case '/':
return leftValue/rightValue;
}
throw new IllegalArgumentException("Error.");
}