I'm trying to parse an arithmetic expression for a Binary Tree using stacks. So far I have:
package home2;
import chapter7.binaryTree.*;
import chapter7.tree.NonEmptyTreeException;
import chapter5.nodeStack.*;
public class Expression {
private NodeStack<LinkedBinaryTree<String>> stack = new NodeStack<>();
private String sym;
LinkedBinaryTree<String> expression;
LinkedBinaryTree<String> branch = new LinkedBinaryTree<>();
LinkedBinaryTree<String> branchtwo = new LinkedBinaryTree<>();
public LinkedBinaryTree<String> buildTree(String E) throws NonEmptyTreeException, EmptyStackException{
for (int i = 0; i < E.length(); i++){
sym = E.substring(i, i+1);
if ( sym.equals(")")) {
try{
branchtwo = stack.pop();
expression = stack.pop();
branch = stack.pop();
expression.attach(expression.root(), branch, branchtwo);
stack.push(expression);
}catch ( EmptyStackException e){}
}else{
expression = new LinkedBinaryTree<>();
expression.addRoot(sym);
stack.push(expression);
}
}// end for loop
return stack.pop();
}// end method
}// end class
Right now my test outputs:
The Original String(((3+1)3)/((9-5)+2))-((3(7-4))+6)
Copied as Tree Structure[+, (, *, -, 7, 4, 6]
From running the debugger I found that my expression method splices the expression into 3 trees in the stack rather than just having one giant tree inside it. I'm guessing my problem starts there, but I'm unsure how to approach it. Any input is welcome.
Thanks.