【问题标题】:Printing a binary tree using InOrder traversal without ambiguity使用无歧义的 InOrder 遍历打印二叉树
【发布时间】:2013-03-06 17:03:27
【问题描述】:

我正在尝试使用中序遍历(在 java 中)打印出二叉树,但没有任何歧义。

我从后序符号输入创建了树。

例如,输入 = 2 3 4 * - 5 + 然后我创建树,并希望使用中序遍历将其打印出来。

所以输出必须是 = 2 - (3*4) + 5 但是,使用中序遍历显然不会给我分隔括号。

我的问题是,我可以按我想要的方式打印输出,而无需干预基本的 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,如果我没有正确发布,请放过我 :)

【问题讨论】:

    标签: binary-tree traversal ambiguity inorder


    【解决方案1】:

    我想通了,例如,输入 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
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      相关资源
      最近更新 更多