我正在尝试使用按顺序遍历(在java中)打印出二叉树,但没有任何歧义。
我从一个后序符号输入创建了这个树。
例如:input = 2 3 4 * - 5 +然后我创建了树,并希望使用顺序遍历将其打印出来。
所以输出一定是= 2 - (3*4)+ 5然而,使用using in-order遍历显然不能给我分隔括号。
我的问题是,我可以打印输出我想要的方式,而不干预基本的BinaryNode和BinaryTree类,但只改变我的驱动程序类?如果是这样,我该怎么做呢?
如果我只能通过改变printInOrder方法(在BinaryNode类中)来做到这一点,那么到目前为止它看起来是这样的:
public void printInOrder()
{
if (left != null)
{
left.printInOrder(); // Left
}
System.out.print(element); // Node
if (right != null)
{
right.printInOrder(); // Right
}
}
这是我第一次在Stack Overflow上发帖,如果我发错了请原谅我:)
我算出来了,所以例如,输入23+4+5*将得到输出(((2+3)+4)*5)
见下面代码:
//NOTE: printInOrder has been modified to exclude ambiguity
public void printInOrder()
{
if (left != null)
{
if (height(left)== 0)
{
//when we reache the bottom of a node, we put a bracket around each side as we know this will have it's own operation
// eg: *
// /
// 3 4
System.out.print("(");
left.printInOrder(); // Left
}
else
{
// We also put in a bracket here as this matches the closing brackets to come (which we do not know about yet)
System.out.print("(");
left.printInOrder(); // Left
}
}
System.out.print(element); // Node
if (right != null)
{
if (height(right) == 0)
{
//when we reache the bottom of a node, we put a bracket around each side as we know this will have it's own operation
// eg: *
// /
// 3 4
right.printInOrder(); // Right
System.out.print(")");
}
else
{
right.printInOrder(); // Right
// System.out.print(")"); // this print statement actually isnt necessary
}
}
}