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

前端 未结 2 844
攒了一身酷
攒了一身酷 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:34

    This code only yields leaves that are (immediate) children of the root. The other ones get visited, they yield to the upper function, but the upper function does nothing with them. What you need is to yield them from the lower function to the upper one:

    def paths(self, acc=[]):
        if self.is_leaf():
            yield [self.node]+acc
    
        for child in self.children:
            for leaf_path in child.paths([self.node]+acc): # these two
                yield leaf_path                            # lines do that
    

    This should do the trick.

提交回复
热议问题