Java 统计BST中的插入数
我有一个BST字符串类,其中包含一个名为numInsertions的全局变量,该变量统计我插入BST的次数。我不确定这是否会给出正确的结果,因为我不太了解递归,请帮助我验证Java 统计BST中的插入数,java,recursion,binary-search-tree,Java,Recursion,Binary Search Tree,我有一个BST字符串类,其中包含一个名为numInsertions的全局变量,该变量统计我插入BST的次数。我不确定这是否会给出正确的结果,因为我不太了解递归,请帮助我验证 public void insert(String key) { if(isEmpty()) { root = new Node(key); numInsertions++; } else numInsertions = 1+insert(key, ro
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;
}
为您的类编写一个测试用例,并测试该类是否正常运行。假设您的类名为BST,您可以使用名为“size”的方法访问实例变量“numberOfInserts”,可以在测试类的主方法中放置一个简单的测试用例,用于测试插入,无需任何第三方库。比如:
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尝试调试应用程序