我花了一段时间我不知道。我想进行逆序遍历(从右到左),并将根的级别传递给函数ShowTree。
根的级别到底是什么?是高度吗?如果是,这是它的代码:

public int getHeight()
{
    return getHeight(_root);
}
private int getHeight (BSTnode top)
{
    if (top == null)
        return 0;
    else
    {
        int lftHeight = getHeight(top._left);
        int rhtHeight = getHeight(top._right);
        if (lftHeight > rhtHeight)
            return 1 + lftHeight;
        else
            return 1 + rhtHeight;
    }
}


因此,我将getHeight的值分配给level并将其传递给ShowTree。我想使用每个节点的级别来计算要在每个节点的数据前面插入多少空间。

public String ShowTree (int level)
{
    return ShowTree(_root,level);
}
private String ShowTree(BSTnode myroot, int level)
{
    String result = "";
    if (myroot == null)
        return "";
    else
    {
        result += ShowTree (myroot._right, level + 1);
        result += myroot._data.toStringKey();
        result += ShowTree (myroot._left, level + 1);
        return result;
    }
}


但是,这样会使树变暗:

C

b

一种

当它应该像这样打印时:

      c


b

                 a

最佳答案

在您的ShowTree(BSTnode, int)方法中...

String result = ""; // no extra whitespace


你不是说...

String result = " "; //extra whitespace

09-27 06:42