Traverse every unique path (from root to leaf) in an arbitrary tree structure

前端 未结 4 1246
执念已碎
执念已碎 2021-01-31 12:18

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 = [\"c         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 13:03

    So basically you are doing a depth first search, but rather than tracking the visiting of the nodes explicitly in a non-destructive way, or maintaining enough context to search without tracking, you are destroying the tree to do this tracking.

    The traditional way to convert this to a plain DFS would be to loop around your recursion condition, basically change the child recursive call to something like:

    } else {
      for (Node child = node.firstChild(); node != null; node = node.nextChild()) {
          traverse(child);
      }
    }
    

    This will traverse all your children, and you can pretty much remove the node.isLeaf case, since backtracking is done automatically for you. Note that I made up the nextChild function since I can't see what it's called in your code, but you must have something similar, or some way to iterate through the children.

    An alternate way that preserves more of the structure of your existing code would be to maintain a separate data structure which contains a set of "visited" nodes, this could be as simple as a Set of strings if all your node names are unique - rather than delete the node, add it to the "visited" set, and in your recursion condition, don't check for null, but rather find the first unvisited node. This is probably more complicated than the suggestion above, but might be more similar to what you have now - and would avoid loops in the case you ever need to do this on a cyclic graph rather than a tree.

提交回复
热议问题