我研究了好久了,还是没明白。我应该进行逆序遍历(右-根-左)并将根的级别传递给函数 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
关于java - 二叉搜索树 : Display contents of the tree in a tree like fashion (recursive),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20498712/