简体   繁体   English

Java-为什么我的递归Draw树方法无法正确输出

[英]Java- Why is my recursive Draw tree method not outputting correctly

I implemented a heap using an array and i'm trying to draw a tree out of the elements in the array. 我使用数组实现了一个堆,并且试图从数组中的元素中绘制一棵树。 Here is my method. 这是我的方法。

public void DrawTree(Job[] a,int index,int pre_space){
    for (int i=0;i<pre_space;i++)
           System.out.print(" ");

System.out.print(a[index].getName()+":"+index );

if (2*index<=element_count&&2*index+1<=element_count){ //if it has both children
        System.out.println();

    for (int i=0;i<pre_space;i++)
            System.out.print(" ");

    System.out.print("/");
    System.out.println("\\");

        DrawTree(a,2*index,pre_space-8);
    DrawTree(a,2*index+1,3);

    }

else if (2*index<=element_count){ //if it only has a left child

System.out.println();

for (int i=0;i<pre_space;i++)
            System.out.print(" ");

    System.out.println("/");
        DrawTree(a,2*index,pre_space-3);

     }


    }

I am outputting the index as well for understandability. 为了便于理解,我也输出了索引。 Here is the output I got: 这是我得到的输出:

          whateve:1
          /\
  Robin:2
  /
Roudy:4   Romy:3

Romy should be on the same line as Robin, and from what I understand, when I call the DrawTree method for the right child(Romy) it will backtrack to the appropriate line. Romy应该与Robin处于同一行,据我了解,当我为正确的child(Romy)调用DrawTree方法时,它将回溯到适当的行。

As stated in the comment, the scheme you are using is a pre-order traversal, so for example if we have a tree : 如评论中所述,您正在使用的方案是预遍历,因此例如,如果我们有一棵树:

              1
             / \
            2   3
           / \
          4   5

When you traverse to node 2, you output some additional lines before you can go to node 3. 遍历到节点2时,需要输出一些额外的行,然后才能转到节点3。

The order is 1 -> output some line ->2 -> output some lines -> 4 -> 5 ->3, so at node 3, we now has at least 2 lines between node 1 and 3. 顺序是1->输出一些行-> 2->输出一些行-> 4-> 5-> 3,因此在节点3上,我们现在在节点1和3之间至少有2条线。

So what you should do is using an ArrayList<ArrayList<String>> lines , with each element ArrayList<String> in lines represent one line. 所以,你应该是使用做什么ArrayList<ArrayList<String>> lines ,每一个元素ArrayList<String>lines代表一行。

Note : this problem is far complicated than your current implementation as between each level of the tree, we need to give enough space to display all of its successors. 注意 :这个问题比您当前的实现复杂得多,因为在树的每个级别之间,我们需要提供足够的空间来显示其所有后继对象。 So you need to pre-calculate the necessary space (depending on the size of the sub-tree at each node) before print them out. 因此,在打印出来之前,您需要预先计算必要的空间(取决于每个节点上子树的大小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM