我正在尝试使用堆栈解析二进制树的算术表达式。到目前为止,我有:
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
现在我的测试输出:
原始字符串(((3 + 1) 3)/((9-5)+2)) - ((3 (7-4))+ 6)
复制为树状结构[+,(,*, - ,7,4,6)
从运行调试器开始,我发现我的表达式方法将表达式拼接到堆栈中的3棵树中,而不是只在其中放置一棵巨树。我猜我的问题从那里开始,但我不确定如何处理它。欢迎任何意见。
感谢。