我有一个BST类的字符串,其中包含一个名为numInsertions
的全局变量,它计算我在BST中执行的插入次数。我不确定这会给出正确的结果,因为我不太了解递归,请帮我验证
public void insert(String key)
{
if(isEmpty())
{
root = new Node(key);
numInsertions++;
}
else
numInsertions = 1+insert(key, root);
}
public int insert(String key, Node curr)
{
int result = 1;
if(key.compareTo(curr.getKey())<0)
{
if(curr.getLeftChild()==null)
{
Node newNode = new Node(key);
curr.setLeftChild(newNode);
}
else
result = result +insert(key,curr.getLeftChild());
}
else
{
if(curr.getRightChild()==null)
{
Node newNode = new Node(key);
curr.setRightChild(newNode);
}
else
result = result +insert(key,curr.getRightChild());
}
return result;
}
答案 0 :(得分:0)
为您的类编写测试用例并测试该类的行为是否正常。我们假设您的班级名为BST,您可以访问实例变量&#39; numberOfInserts&#39;使用名为&#39; size()&#39;的方法,可以在测试类的main方法中放置一个用于测试插入的简单测试用例(没有任何第三方库)。类似的东西:
BST bst = new BST();
//test insertion of 100 items
for ( int i = 0; i < 100; i++ ){
bst.insert(String.valueOf(i));
if ( bst.size() != i+1 ){
throw new Exception("Invalid BST size " + bst.size());
}
}
在此示例中,如果类的行为不正确,则会抛出异常。如果它行为不当,您可以进入调试器(或使用System.out.println)来尝试调试应用程序。