2016-04-03 9 views
0

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; 
} 
} 
+1

Zaten denediniz mi? – jbapple

+1

Evet, lütfen 'add()' yöntemini yazmaya çalışın. Bir hata bulduğunuzda, burada bir soru sorun. – markspace

+0

Ü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

cevap

0
BSTNode current = m_root; 
if(current == null) { 
    current = new BSTNode(v); 
    return; 
} 
while(true) { 
    if(current.key > v) { 
     if(current.left == null) { 
      current.left = new BSTNode(v); 
      break; 
     } 
     else 
      current = current.left; 
    } 
    else if(current.key < v) { 
     if(current.right == null) { 
      current.right = new BSTNode(v); 
      breakl; 
     } 
     else current = current.right; 
    } 
} 
+0

Bu işe yaradı ama meraktan kaçtı .key ne anlama geliyor? Henüz görmedim – Jennifer

+1

Ben buna çağırabilirim. Daha iyi :) –

1

bunu çözdü!

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) 
    {current=null;} 
    else 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(); 
    }} 
    } 
    }