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;
}
}
Czy przemierzaj dzieci, a wszystkie dzieci, które mają puste listy dzieci, mają urlop? W czym problem? – SMA
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. –
problem rozwiązany, dziękuję wszystkim – Frank