0
我有一個BST類別的字符串,其全局變量名爲numInsertions
,它計算我在BST中插入的次數。我不知道這給正確的結果,因爲我不知道遞歸非常好,請幫我覈實在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;
}