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

前端 未结 4 1253
执念已碎
执念已碎 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:18

    OK. I think you actually mean that you want to find every path from root to a leaf.

    Then (a un-optimized version)

    void traverse (Node root) {
      // assume root != NULL
      traverse (root, new LinkedList());
    }
    
    private void traverse (Node root, LinkedList path) {
      path.add(root);
      if (root.isLeaf()) {
        print path;
      }
      else {
        for each node of root {
          traverse (node, new LinkedList(path));
        }
      }
    }
    

提交回复
热议问题