【问题标题】:Binary Search Tree: Display contents of the tree in a tree like fashion (recursive)二叉搜索树:以类似树的方式显示树的内容(递归)
【发布时间】:2013-12-28 05:17:19
【问题描述】:

我已经搞了一段时间了,我想不通。我想进行逆序遍历(右-根-左)并将根的级别传递给函数 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

【问题讨论】:

  • 两件快事: 1. 你真的需要'level' 变量吗?您没有在代码中使用它,并且空格数(也称为深度)是由递归的隐式循环计算的。 2. 将‘树’传递给公共方法而不是关卡不是更符合逻辑吗?

标签: java recursion tree binary-search-tree


【解决方案1】:

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

String result = ""; // no extra whitespace

你的意思是……

String result = " "; //extra whitespace

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2011-07-19
    • 2013-04-14
    相关资源
    最近更新 更多