试图显示树

时间:2018-04-16 22:13:51

标签: java tree

我正在编写一个程序,可以显示一个家庭树,其中孩子在左边,他们的兄弟在右边。这样的树看起来如下:

                              gradfather
                             /       \
                            child     gradfathers sibling
                           /    \
               childs child      childs first sibling
                                  \
                                   childs second sibling etc

我知道这可能有点奇怪,但我正在尝试练习图表。无论如何,我正在尝试编写一个可以显示树的方法,我不太确定我的逻辑是否正确。我的代码如下

public void printTree() {
    Node current = root;
    Node parent;
    while (current.left != null) {
        System.out.print("Great-Great Gradfather is: " + root);
        current = current.left;
        parent = current;
        if (current.right != null) {
            System.out.print("His children are: ");
            while (current.right != null) {
                System.out.print(current + " ");
                current = current.right;
            }
        }
        current = parent;
        current = current.left;
        parent = current;
    }
}

我希望得到的输出是

your Great grandfather was name

his children were names

they're children were names

your siblings are names

编写一个更简单的打印函数会更有效率,该函数显示当时的“当前”根,只显示兄弟姐妹,并在我的主要文件中System.out.print说“他们的孩子是”,然后打印。就像每次都可以将电流迭代到current.left一样?或者我使用一种大型印刷方法走在正确的轨道上?

谢谢你们。

1 个答案:

答案 0 :(得分:-1)

注意:每个“sibbling”应该在“树中的相同级别”