美文网首页
优雅实现二叉树的中序遍历

优雅实现二叉树的中序遍历

作者: 洛克黄瓜 | 来源:发表于2019-03-19 17:49 被阅读0次

    Visitor模式实现

    class TreeNode:
        def __init__(self, data):
            self.data = data
            self.left = None
            self.right = None
        def accept(self, visitor):
            if self.left is not None:
                self.left.accept(visitor)
    
            visitor.visit(self)
    
            if self.right is not None:
                self.right.accept(visitor)
    
    class PrintVisitor:
        def visit(self,node):
            print(node.data)
    
    root = TreeNode('1')
    root.left = TreeNode('2')
    root.right = TreeNode('3')
    
    visitor = PrintVisitor()
    
    root.accept(visitor)   #输出2, 1, 3
    

    iter结合生成器来实现

    class TreeNode:
        def __init__(self, data):
            self.data = data
            self.left = None
            self.right = None
    
        def __iter__(self):
            return self.__generator()
    
        def __generator(self):
            if self.left is not None:
                yield from iter(self.left) 
            yield from self.data
    
            if self.right is not None:
                yield from iter(self.right) 
    
    root = TreeNode('1')
    root.left = TreeNode('2')
    root.right = TreeNode('3')
    
    for ele in root:
        print(ele)
    

    相关文章

      网友评论

          本文标题:优雅实现二叉树的中序遍历

          本文链接:https://www.haomeiwen.com/subject/oyunmqtx.html