我想打印我的树来中缀。 我的问题出在哪里?请帮助我。[在此处输入图像描述][1] 谢谢。 其他表达式在类中完美实现。
public class SyntaxTree extends LinkedBinaryTree<String> {
public static SyntaxTree buildSyntaxTree(String[] expr) {
Stack<SyntaxTree> stack = new Stack<>();
for(int i =0; i < expr.length; i++) {
if (expr[i].equals("+") || expr[i].equals("-") || expr[i].equals("*") || expr[i].equals("/")) {
SyntaxTree subtree = new SyntaxTree();
subtree.addRoot(expr[i]);
SyntaxTree righttree = stack.pop();
SyntaxTree lefttree = stack.pop();
subtree.attach(subtree.root(), lefttree, righttree);
stack.push(subtree);
}
else {
SyntaxTree subtree = new SyntaxTree();
subtree.addRoot(expr[i]);
stack.push(subtree);
}
}
SyntaxTree res = stack.pop();
return res;
}
public String parenthesize() {
String ret = "";
List<Node<String>> ls = inOrder();
for (Node<String> node : ls) {
if (isLeftChild(node)) ret += "(";
String e = node.getElement();
if (e.equals("+") ||e.equals("-") || e.equals("/") || e.equals("*")) {
if (node.getLeft() != null) {
String l = node.getLeft().getElement();
if (!l.equals("+") && !l.equals("-") && !l.equals("/") && !l.equals("*")) {
ret += l;
}
}
ret += " " + e + " ";
if (node.getRight() != null) {
String r = node.getRight().getElement();
if (!r.equals("+") && !r.equals("-") && !r.equals("/") && !r.equals("*")) {
ret += r;
}
}
}
if (isRightChild(node)) ret += ")";
}
return ret;
<小时/>
预期:((1 + 2) * (3 + ((4/2) * 5))) 实际:((1 + 2) * (3 + )((4/2) * 5))
最佳答案
像这样怎么样:
public String parenthesize(Node<String> node) {
if (node == null) {
return "";
}
String e = node.getElement();
if (e.equals("+") ||e.equals("-") || e.equals("/") || e.equals("*")) {
return "(" + parenthesize(node.getLeftChild())
+ e + parenthesize(node.getRightChild()) + ")";
}
return e;
}
关于java - 如何从树中打印中缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62339042/