2015-11-19 42 views
0

我需要找到給定的節點,然後返回它或null,如果它沒有找到它。通過N-ary樹搜索並返回節點

我已經試過這一點,但它返回null:

public NodoN<T> buscarNodo(T dato, NodoN<T> nodo){ 
     if(nodo != null) { 
      // Root is dummy and is null 
      if (nodo.dato != null && nodo.dato.equals(dato)){ 
       return nodo; 
      } else { 
       int cantHijos = nodo.nodos.size(); 
       ArrayList<NodoN<T>> nodosHijos = nodo.nodos; 
       NodoN<T> nodoEncontrado; 
       for (int i = 0; i < cantHijos; i++) { 
        nodoEncontrado = buscarNodo(dato, nodosHijos.get(i)); 
        if(nodoEncontrado.dato.equals(dato)){ 
         return nodo; 
        } 
       } 
      } 
     } 
     return null; 
} 

當在調試程序看,它正確地發現,我想要的,但隨後保持在循環會並返回null。

NodoN類:

import java.util.ArrayList; 

public class NodoN<T> { 
    T dato; 
    Integer tMax; 
    ArrayList<NodoN<T>> nodos; 

    public NodoN(T dato, Integer tMax){ 
     this.dato = dato; 
     this.tMax = tMax; 
     nodos = new ArrayList<NodoN<T>>(); 
    } 

    public void agregar(NodoN<T> nodo){ 
     if (nodos.size()<tMax){ 
      nodos.add(nodo); 
     }else{ 
      nodos.get(0).agregar(nodo); 
     } 

    } 

    String inOrder(boolean ingnorarRaiz){ 
     String ret = ""; 

     if (!ingnorarRaiz){ 
      ret =ret + dato.toString() + ","; 
     } 

     for (int i=0;i<nodos.size();i++){ 
      ret = ret + nodos.get(i).inOrder(false); 
     } 

     return ret; 

    } 


} 
+0

你是什麼意思,「當看着調試器,它正確地找到我想要的,但繼續在循環中並返回空值」?如果它已經找到你想要的那個,它怎麼能返回null? – jiaweizhang

+0

@jiaweizhang我的意思是我找不到返回節點的時候。執行應該停止並返回,這是因爲它是遞歸的,我總是遇到它的問題哈哈 – JorgeeFG

回答