Python (yield): all paths from leaves to root in a tree

前端 未结 2 928
攒了一身酷
攒了一身酷 2021-01-13 11:20

I want to generate all paths from every leaf to root in a tree. I\'d like to do that with generators, to save memory (tree can be big). Here\'s my code:

def          


        
2条回答
  •  执念已碎
    2021-01-13 11:36

    At the moment the for loop doesn't yield anything. It should instead yield all the elements that are generated by the recursive call:

    for child in self.children:
        for path in child.paths([self.node]+acc):
            yield path
    

提交回复
热议问题