Bu Veri Yapısı sorununu çözmek için biraz yönlendirmeye ihtiyacım var. Bir BST için bir add() yöntemi oluşturmalıyım. Bu soruna özyineli çözümün nasıl yapılacağını biliyorum ama bunun için tekrarlayıcı olmayan bir çözüm nedir? İşte benim sınıfım.BST add() yöntemi
import java.util.*;
public class BST
{
// instance variables
private BSTNode m_root;
private int m_size;
// constructor
public BST()
{
m_root = null;
m_size = 0;
}
// add a value into the tree
public void add(int v)
{ BSTNode current = m_root;
if(current == null) {
m_root=new BSTNode(v);
m_size++;
}
else
{
while(current!=null) {
if(current.getInfo() > v) {
if(current.getLeft() == null) {
m_root.setLeft(new BSTNode(v));
m_size++;
current=null;
}
else
current = current.getLeft();
}
else if(current.getInfo()< v) {
if(current.getRight() == null) {
m_root.setRight(new BSTNode(v));
current=null;
m_size++;
}
else current = current.getRight();
}}}}
// get the size of the tree
public int size()
{
return m_size;
}
// empty the tree
public void clear()
{
m_root = null;
m_size = 0;
}
}
Zaten denediniz mi? – jbapple
Evet, lütfen 'add()' yöntemini yazmaya çalışın. Bir hata bulduğunuzda, burada bir soru sorun. – markspace
Üzgünüm, biraz dağınık, bu yüzden ben yapmadım. Aşağıdaki cevabın yardımıyla biraz değiştirdim ama bu da işe yaramadı ... – Jennifer