如何通过递归方法来保持BST数组填充时的计数
我想通过预置树遍历来填充数组,但我认为我已经在如何保留计数器正确。我的toString()方法调用preorder方法,但它只输出null。我怎样才能解决这个问题?如何通过递归方法来保持BST数组填充时的计数
public AVLTreeNode[] preorder() {
/*
* return an array of AVLTreeNodes in preorder
*/
AVLTreeNode[] preorder = new AVLTreeNode[size];
int count = 0;
return preorder(root, count, preorder);
}
private AVLTreeNode[] preorder(AVLTreeNode data, int count, AVLTreeNode preorder[])
{
if (data == null)
{
return preorder;
}
preorder[count] = data;
if (data.getLeft() != null)
{
preorder(data.getLeft(), count++, preorder);
}
if (data.getRight() != null)
{
preorder(data.getRight(), count++, preorder);
}
return preorder;
}
回答:
count有错误的价值,因为与count++的preorder后续调用的count实际值传递给方法和事后count增加。在从左节点count返回后,其值可能会比传递给右节点的呼叫的值高。解决办法有两个:
使用全局
private int count;,并呼吁preorder之前将其设置为0。返回新
count代替AVLTreeNode[]并将其分配给该方法的本地count,以获得正确的值。AVLTreeNode[] preorder也可以是一个私有变量。
以上是 如何通过递归方法来保持BST数组填充时的计数 的全部内容, 来源链接: utcz.com/qa/257773.html

