I have a few 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 will convert this structure to 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 print every unique path in the tree (excluding the root):
a0 -> b0 -> c1 -> d0 a0 -> b0 -> c1 -> d1 a0 -> b1 -> c1 -> d0 ... a1 -> b2 -> c1 -> d1
I do this by "destroying" the tree itself while traversing it as follows:
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()) {
traverse(Node) always prints the first available tree path (from root to leaf), and delete(Node) cuts the leaves of a tree that has already been visited by traverse(Node) .
This works as intended, but I really want to find a solution to cross the tree in the previously described way without destroying it. If there is a way to do this, I would be interested to go through the same structure, but in the form of a graph to reduce redundancy.
algorithm data-structures tree
Kohányi Róbert
source share