我想改變我的BST的遞歸插入方法到非遞歸(也許while循環) 這種變化的原因,因爲我想看看是否有可能。將(二叉搜索樹)的遞歸插入更改爲非遞歸?
這裏是插入的代碼:
public void insert(String value)
{
//The node is stored in the root
root = insert(value,root);
}
private Character insert(String value,Character current)
{
if(current == null)
{
//Add the root if the tree empty
current = new Character(value);
}
else
//If the value that we want to insert < root value, then keep going to left till
//it's empty then inserted at left end. Done by recursion
if(value.compareTo(current.getElement())<=-1)
{
current.setLeft(insert(value,current.getLeft()));
}
else
//If the value that we want to insert > root value, then keep going to right till
//it's empty then inserted at right end. Done by recursion
if(value.compareTo(current.getElement())>=1)
{
current.setRight(insert(value,current.getRight()));
}
else
{
//Else, the number we want to insert in already in the tree
System.out.println("Duplicate numbers inserted" + current.getElement());
}
//returning the node tree so that we store it in the root
return current;
}
我可以改變這個代碼轉換成非遞歸?
乾杯
如果原因是要查看是否有可能,那麼不要擔心。它是。 – Maroun 2013-04-20 07:37:52