9
I have several lists:
A = ["a0", "a1"] // the number of lists varies
B = ["b0", "b1", "b2"] // such as the number of elements in a list.
C = ["c1"]
D = ["d0", "d1"]
I convert this structure into a tree:
_____ROOT______
/ \
___a0____ ____a1____
/ | \ / | \
b0 b1 b2 b0 b1 b2
| | | | | |
c1 c1 c1 c1 c1 c1
/ | / | / | / | / | / |
d0 d1 d0 d1 d0 d1 d0 d1 d0 d1 d0 d1
I'm printing every unique path in the tree (omitting the root):
a0 -> b0 -> c1 -> d0
a0 -> b0 -> c1 -> d1
a0 -> b1 -> c1 -> d0
...
a1 -> b2 -> c1 -> d1
I'm doing this by "destroying" the tree itself while traversing it in the following way:
public static void delete(Node node) {
if (node.isLeaf() && !node.isRoot()) {
Node parent = node.getParent();
parent.removeChild(node);
delete(parent);
}
}
public static void traverse(Node node) {
if (node.isRoot())
System.out.println("---");
else
System.out.println(node.getName());
if (node.isLeaf()) { // I'm still working on
if (!node.isRoot()) { // removing unnecessary checks
delete(node);
traverse(node.getRoot());
}
} else {
Node child = node.firstChild();
if (null != child)
traverse(child);
}
}
traverse(Node) always prints the first available path of the tree (from root to leaf) while delete(Node) cuts leafs of the tree that is already visited by traverse(Node).
This works as intended, but I'm keen to find a solution to traverse the tree in the previously described way without destroying it. If there's a way to do this then I'd be interested to traverse this same st