2012-10-07 1 views
1

J'ai écrit un code pour insérer dans l'arbre binaire un type d'élément générique qui est trié par leur nom. Ne pense pas que c'est correct cependant.java binary tree insert function non récursive

public boolean insert(E e) { 
    BTNode temp = root; 
    if (root == null) { 
     root.setElement(e); 
    } 
    while (temp != null) 
    if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
     temp = temp.getRight(); 
    } else { 
     temp = temp.getLeft(); 
    } 
    temp.setElement(e); 
    return true; 
} 

Pouvez-vous me suggérer des corrections?

+1

Et quelle est la question? – Augusto

+4

Supprimez le point-virgule après l'instruction while. –

+0

'temp' - un excellent choix de nom de variable. –

Répondre

2

Un insert aurait besoin de créer un nouveau nœud. Je ne sais pas comment les créer car je n'ai pas vu le constucteur, mais je suggère quelque chose comme:

public boolean insert(E e) {   
    if (root == null) { 
     root = new BTNode(); 
     root.setElement(e); //how would this work with a null root? 
     return true; //that's it, we're done (when is this ever false by the way?) 
    } 
    BTNode current = root; 
    while (true) { //brackets! indenting is important for readabilty 
     BTNode parent=current; 
     if (current.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
      current = current.getRight(); 
      if(current==null) { //we don't have a right node, need to make one 
       current = new BTNode(); 
       parent.setRight(current); 
       break; //we have a new node in "current" that is empty 
      } 
     } else { 
      current= current.getLeft(); 
      if(current==null) { //we don't have a left node, need to make one 
       current = new BTNode(); 
       parent.setLeft(current); 
       break; //we have a new node in "current" that is empty 
      } 
     } 
    } 
    current.setElement(e); 
    return true; 
} 
-1

qu'Amadeus mentionné, la boucle while ne devrait pas avoir un point-virgule à la fin:

BTNode temp = root; 
    if (root == null) { 
     root.setElement(e); 
     return; 
    } 
    while (temp != null) 
    { 
     if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
      if(temp.getRight() != null) 
      temp = temp.getRight(); 
      else 
      { 
       temp.createRight(e); 
       temp = null; //or break 
      } 
     } else { 
      if(temp.getLeft() != null) 
      temp = temp.getLeft(); 
      else 
      { 
       temp.createLeft(e); 
       temp = null; //or break 
      } 
     } 
    } 

    return true; 
+0

-1 et comme je l'ai mentionné: Alors la ligne temp.setElement (e); est toujours une exception de pointeur nul. – weston

+0

Une autre solution serait d'attraper l'exception et de gérer la création du nœud dans le bloc 'catch' ... moche si ... –

+0

Encore mal 'temp = null;' alors comment cela arrêtera-t-il le NPE? – weston