2015-07-13 15 views
6

Załóżmy, że mam węzeł w drzewie, w jaki sposób mogę uzyskać wszystkie węzły liści, których przodkiem jest ten węzeł? Zdefiniowałem TreeNode w następujący sposób:Jak uzyskać wszystkie węzły liści drzewa?

public class TreeNode<T> 
{ 
    /** all children of the node */ 
    private List<TreeNode<T>> children = new ArrayList<TreeNode<T>>(); 
    /** the parent of the node, if the node is root, parent = null */ 
    private TreeNode<T> parent = null; 
    /** the stored data of the node */ 
    private T data = null; 

    /** the method I want to implement */ 
    public Set<TreeNode<T>> getAllLeafNodes() 
    { 
     Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>(); 
     return leafNodes; 
    } 
} 
+1

Czy przemierzaj dzieci, a wszystkie dzieci, które mają puste listy dzieci, mają urlop? W czym problem? – SMA

+0

Węzeł liści powinien mieć pustą listę dzieci; więc możesz zaimplementować metodę isLeaf() na swoim węźle. A następnie będziesz musiał rekurencyjnie sprawdzić dla wszystkich dzieci twojego węzła. –

+0

problem rozwiązany, dziękuję wszystkim – Frank

Odpowiedz

9

Użyj rekursji.

  • jeśli sam węzeł jest liściem, zwrócić go
  • inaczej, powrót wszystkich liści węzłów swoich dzieci

Coś takiego (nie testowane):

public Set<TreeNode<T>> getAllLeafNodes() { 
    Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>(); 
    if (this.children.isEmpty()) { 
     leafNodes.add(this); 
    } else { 
     for (TreeNode<T> child : this.children) { 
      leafNodes.addAll(child.getAllLeafNodes()); 
     } 
    } 
    return leafNodes; 
} 
+0

Ta metoda nie działa. Próbowałem już wcześniej. Ale dziękuję ci wszystkim. – Frank

+0

Przepraszam, działa, zrobiłem mały błąd. Dzięki! – Frank

+0

działa idealnie! – Frank

Powiązane problemy