I have a generic tree structure. I need an algorithm to traverse it, and remove some leafs if they are not contained in a given list. If all the leafs are removed from a subtree, then remove the whole subtree too.
Example tree:
0
/ | \
1 2 3
/ \ | / \
4 5 6 7 8
Leafs to keep: {4, 6}
Result tree:
0
/ |
1 2
/ |
4 6
The input data structure is contained in a HashMap where the key is the parent id of the nodes, and the value is a List of the Nodes directly under the parent (but not recursively all children). The parent id of the root node is empty string.
Map<String, List<Node>> nodes;
class Node {
private String id;
//other members
//getters, setters
}
I suppose, some kind of recursive DFS traversal algorithm should work, but I couldn't find it out, how.