简体   繁体   English

使用生成器进行二叉树有序遍历

[英]Binary tree inorder traversal using generator

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 returns the Iterator and hence satisfies the Iterable contract. 同样, inorder是一个生成器函数,它返回Iterator并因此满足Iterable合同。 But my code below instead of yielding every node just yields root node which in this case is A . 但是我下面的代码没有产生每个节点,而是产生了根节点,在这种情况下是A What I am doing wrong? 我做错了什么?

Code

from collections import namedtuple

Node = namedtuple('Node', 'data, left, right')

root = Node('A',
        Node('B', Node('D', None, None), Node('E', None, None)),
        Node('C', None, Node('F', None, None)))

class BinaryTree(object):
    def __init__(self, root=None):
        self.root = root

    def __iter__(self):
        return self.inorder(self.root)

    def inorder(self, node):
        if node is None:
            return
        if node.left is not None:
            self.inorder(node.left)
        yield node
        if node.right is not None:
            self.inorder(node.right)

bt = BinaryTree(root)            
for node in bt:
    print node.data

Reference 参考

https://stackoverflow.com/a/6916433/4260745 https://stackoverflow.com/a/6916433/4260745

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. 问题是您调用了self.inorder(node.left) ,但对结果不做任何事情,因此,代码只是简单地执行(延迟执行得很好,这意味着不执行),以及运行时环境继续到下一行。

You need to resolve it by propagating (ie re-yielding ) the elements that are generated by the calls to inorder : 您需要通过传播(即重新生成 )由对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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM