/ / पेड़ के सभी पत्ते नोड्स कैसे प्राप्त करें? - जावा

एक पेड़ के सभी पत्ते नोड्स कैसे प्राप्त करें? - जावा

मान लीजिए कि मेरे पास एक पेड़ में नोड है, मैं सभी पत्ते के नोड्स कैसे प्राप्त कर सकता हूं जिनके पूर्वज इस नोड हैं? मैंने इस तरह TreeNode परिभाषित किया है:

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 के लिए 10

रिकर्सन का प्रयोग करें।

  • अगर नोड खुद ही एक पत्ता है, तो इसे वापस करें
  • अन्यथा, अपने बच्चों के सभी पत्ते-नोड्स लौटें

ऐसा कुछ (परीक्षण नहीं किया गया):

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;
}