显示时如何在节点之间添加链接

时间:2019-04-04 08:10:26

标签: java

我正在尝试使用上述显示功能来显示我的树。 它运作良好,但是,它只需要有关在显示时如何在节点之间添加链接的帮助,以便可以显示树结构。

当前我的显示功能将提供以下输出

enter image description here

但是我希望它通过连接节点的链接显示类似于下图的图像

enter image description here

这是当前打印树的代码

public void display(Node root) // display search tree
    {
        Stack<Node> tStack = new Stack<Node>();
        tStack.push(root);
        int numOfBlanks = 32;
        boolean isRowEmpty = false;
        System.out.println("\n");

        while (isRowEmpty == false) 
        {
            Stack<Node> stack = new Stack<Node>();

            isRowEmpty = true;

            for (int x = 0; x < numOfBlanks; x++)
            {
                System.out.print(" ");
            }

            while (tStack.isEmpty() == false) 
            {
                Node n = (Node)tStack.pop();

                if (n != null)
                {
                    System.out.print(n.value);
                    stack.push(n.left);
                    stack.push(n.right);

                    if (n.left != null || n.right != null)
                    {
                        isRowEmpty = false;
                    }
                }
                else 
                {
                     System.out.print("--");
                     stack.push(null);
                     stack.push(null);
                 }

                for (int y = 0; y < numOfBlanks*2-2; y++)
                {
                     System.out.print(" ");
                }

             }
            System.out.println("\n");

            numOfBlanks /= 2;
            while (stack.isEmpty() == false)
            {
                tStack.push(stack.pop());
            }


        }
        System.out.println("\n");
    }

0 个答案:

没有答案
相关问题