我知道要进行顺序遍历,但我无法弄清楚如何将左孩子与正确的孩子区分开来。我是否应该在什么时候将括号放在叶子上或者我应该做其他事情。我对递归很可怕。我已经让树完美运行了,所以我可以放入一个像(1 + 2)*(3 - 4)这样的表达式,将它转换为postfix并将其添加到树中。我只需要找到一种方法来为每个表达式赋予一组括号。
这是使其工作的代码,感谢dreamcrash算法!
private void printInfix(Node n)
{
if (n != null)
{
if (n.isLeaf())//if n is a leaf, therefore a number
System.out.print(n.element);
else//n is not a leaf
{
System.out.print("(");
printInfix(n.left);
System.out.print(n.element);
printInfix(n.right);
System.out.print(")");
}//end else
}//end if
}
答案 0 :(得分:3)
我做了一些研究,我发现了这个:
Algorithm infix (tree)
/*Print the infix expression for an expression tree.
Pre : tree is a pointer to an expression tree
Post: the infix expression has been printed*/
if (tree not empty)
if (tree token is operand)
print (tree token)
else
print (open parenthesis)
infix (tree left subtree)
print (tree token)
infix (tree right subtree)
print (close parenthesis)
end if
end if
end infix
on http://en.wikipedia.org/wiki/Binary_expression_tree。
我还找到了一个很好的解释和一些代码实现(但在python中)。尽管如此,这个想法仍然是一样的,只是语法问题:http://interactivepython.org/courselib/static/pythonds/Trees/bintreeapps.html
答案 1 :(得分:0)
您应该在父节点中添加括号,而不是子节点。如你所说,你在告诉左孩子的正确孩子时遇到了麻烦。这是因为子节点不知道它是哪个。但是,父节点掌握了这些信息。