如何在Java中实现树格式?

时间:2018-11-05 16:29:17

标签: java tree nodes

我无法将这段代码写成树形格式。我希望它输出为

   x
 x   x
x     x

但它输出为

 x
 x
 x
 ....

如何在代码中添加缩进和空格?如果节点为空,请输入星号或任何符号?

public void insert(int value)
{
    Node n = new Node(value);
    if(root == null)
    root = n;
    else
    {
    Node parent = root;
    while(parent != null)
    {
        if(value < parent.data)
        {
            if(parent.left == null)
            {
               parent.left = n;
               return;
            }
            else
            {
                parent = parent.left;
            }
        }
            else
            {
                if(parent.right == null)
            {
                parent.right = n;
                return;
            }
            else
            {
                parent = parent.right;
            }
            }
        }
    }
}
   private void inOrder(Node n)
   {
    if(n == null)
    return;

   inOrder(n.left);
   System.out.println(n.data + " ");
   inOrder(n.right);
}

public void printInorder()
{
    inOrder(root);
}

1 个答案:

答案 0 :(得分:1)

请检查此Print a binary tree in a pretty way (要么) 您还可以检查此链接https://www.geeksforgeeks.org/print-binary-tree-2-dimensions,在该链接中它以从左到右的顺序而不是从上到下的顺序打印树,等效的Java代码如下所示,其中将根值作为Tree的根节点传递,将空格传递为0

void print2DUtil(Node root, int space) 
{ 
    // Base case 
    if (root == NULL) 
        return; 

    // Increase distance between levels 
    space += COUNT; 

    // Process right child first 
    print2DUtil(root.right, space); 

    // Print current node after space 
    // count 
    printf("\n"); 
    for (int i = COUNT; i < space; i++) 
        printf(" "); 
    printf("%d\n", root.data); 

    // Process left child 
    print2DUtil(root.left, space); 
}