2016-08-09 83 views
2

Ich versuche, einen binären Baum zu machen, die Duplikate nicht akzeptiert ironischerweise habe ich in der Lage, das Gegenteil zu tun:erstellen binären Baum, der keine Duplikate akzeptiert

public void insertLeaf(String a){ 
    Node newNode = new Node(a); 
    if(node==null){ 
     node=newNode; 
     return; 
    } 
    Node currentValue = node; 
    Node parent = null; 
    while(true){ 
     parent = currentValue; 
     if(a.compareTo(currentValue.data)<0){    
      currentValue = currentValue.left; 

      if(currentValue==null){ 
       parent.left = newNode; 
       return; 
      } 
     }else{ 
      currentValue = currentValue.right; 
      if(currentValue==null){ 
       parent.right = newNode; 
       return; 
      } 
     } 
    } 
} 

Heres die Node-Klasse

class Node{ 
    String data; 
    Node left; 
    Node right; 
    public Node(String data){ 
     this.data = data; 
     left = null; 
     right = null; 
    } 
} 

Danke für Ihre Hilfe.

+1

Wie erwarten Sie Duplikate anders zu handhaben, wenn Ihr Code für den Fall um eine spezielle Verarbeitung nicht über, wenn 'compareTo' Null zurückkehrt? – dasblinkenlight

+0

Mögliches Duplikat von [Was ist ein Debugger und wie kann er mir helfen, Probleme zu diagnostizieren?] (Http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help- Ich-Diagnose-Probleme) –

Antwort

2

Das Problem ist Ihre else Klausel - es akzeptiert beide Fälle von a.compareTo(currentValue.data)>0 und a.compareTo(currentValue.data)==0. Es sollte nur die ersteren akzeptieren. Wenn a.compareTo(currentValue.data)==0, sollten Sie den Wert der Struktur nicht hinzufügen.

soll Ihr Zustand sein:

if(a.compareTo(currentValue.data)<0){    
     currentValue = currentValue.left; 
     if(currentValue==null){ 
      parent.left = newNode; 
      return; 
     } 
    } else if (a.compareTo(currentValue.data)>0) { 
     currentValue = currentValue.right; 
     if(currentValue==null){ 
      parent.right = newNode; 
      return; 
     } 
    } else { 
     return; // don't add the a duplicate value 
    } 
+0

oh yeah ich sehe Ihre Logik danke Mann –