I have numerical strings that represent trees (I don’t know if there’s an official name for this):
012323301212
The above example represents 2 trees. The root is signified with 0. Immediate children of the root are ‘1’s, immediate children of ‘1’s are ‘2’s, and so on. I need to group these into sub trees that consist of parents and their immediate children. So the above would be decomposed into…
01 122 23 233 011 12 12
I was thinking one possible way to do this would be to build a tree structure from the string then visit each node and generate a subtree of it and its immediate children (if it had any), but this seems relatively complicated. Is there some clever way I can do this without resorting to creating a tree structure and traversing it?
The output you’re requesting essentially is the tree structure. That said, you can treat your input as a pre-order depth-first traversal and read off the tree structure without holding all of it in memory at once: