【问题标题】:How to implement a tree format in Java?如何在 Java 中实现树形格式?
【发布时间】:2018-11-05 16:29:17
【问题描述】:

我在将这部分代码写成树格式时遇到了问题。我希望它输出为

   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);
}

【问题讨论】:

    标签: java tree nodes


    【解决方案1】:

    请查看Print a binary tree in a pretty way (要么) 您也可以检查此链接https://www.geeksforgeeks.org/print-binary-tree-2-dimensions,其中它以从左到右的顺序而不是从上到下的顺序打印树,等效的 java 代码如下,其中将根值作为树的根节点传递,空间为 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); 
    } 
    

    【讨论】:

    • 您提供的链接很有用,但其中一个是基于 C++ 的,另一个是基于 PHP 的,它们都与 Java 无关。除非您提取基本想法,否则您的答案可能对 OP 毫无帮助。
    • @aka-one 和 Zoe 我想在问题下方添加评论,但似乎我没有足够的声誉来做到这一点,所以想回答/指向有用的资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多