好吧,我明白了。這是我已經達到的解決方案。我相信雖然有更好的解決方案 - 歡迎您糾正我。
// kick off the recursion
public Map<Integer, Integer> findLeafOnlyParents(GenericTree<Integer> tree){
Map<Integer, Integer> resultMap = new HashMap<>();
// start search from the root
traverseWithDepth(tree.getRoot(), resultMap, 0);
return resultMap;
}
private void traverseWithDepth(GenericTreeNode<Integer> node, Map<Integer, Integer> traversalResult, int depth) {
// check if the current note in the traversal is parent Of leaf-only nodes
if (isParentOfLeafOnly(node)){
traversalResult.put(node.data, depth);
}
// check the node's children
for(GenericTreeNode<Integer> child : node.getChildren()) {
traverseWithDepth(child, traversalResult, depth + 1);
}
}
// the main logic is here
private boolean isParentOfLeafOnly(GenericTreeNode<Integer> node){
boolean isParentOfLeafOnly = false;
// check if the node has children
if(node.getChildren().size() > 0){
// check the children of the node - they should not have children
List<GenericTreeNode<Integer>> children = node.getChildren();
boolean grandChildrenExist = false;
// for each child check if it has children of its own
for(GenericTreeNode<Integer> child : children) {
grandChildrenExist = child.getChildren().size() > 0;
// once found note that the current node has grandchildren,
// so we don't need to check the rest of the children of the node
if (grandChildrenExist){
break;
}
}
// we need only the parents who don't have great children
isParentOfLeafOnly = !grandChildrenExist;
}
return isParentOfLeafOnly;
}