I hate recursion, I can’t trace through the code easily, but with trees I don’t have a choice.
This is what I’ve tried so far.
private int evaluate(Node n)
{
if (n != null)
{
if (n.isLeaf()) // n is a node with a number
return Integer.parseInt(n.element);
else
{
int left = evaluate(n.left);
int right = evaluate(n.right);
return calculate(left, n.element, right);
} //end else
} //end if
} //end evaluate
Do you mean:
I assume your node is an operation, ie “+”, “-” etc.
Your “calculate” has to execute the corresponding operation on the int “left” and “right” and you are done!