Binary tree inorder traversal using generator

前端 未结 1 1716
甜味超标
甜味超标 2021-01-16 12:18

Description

I want my Binary tree to be iterable so that I can loop though it to visit every node once. Also, inorder is a generator function which re

1条回答
  •  借酒劲吻你
    2021-01-16 12:45

    The problem is that you call self.inorder(node.left), but don't do anything with the result, and as a result, the code is simply executed (well executed lazily, which means not executed), and the runtime environment continues to the next line.

    You need to resolve it by propagating (i.e. re-yielding) the elements that are generated by the calls to inorder:

        def inorder(self, node):
            if node is None:
                return
            if node.left is not None:
                for x in self.inorder(node.left) :
                    # you need to *re-yield* the elements of the left and right child
                    yield x
            yield node
            if node.right is not None:
                for x in self.inorder(node.right) :
                    yield x
    

    0 讨论(0)
提交回复
热议问题