PegasusWang / python_data_structures_and_algorithms

Python 中文数据结构和算法教程

Home Page:http://pegasuswang.github.io/python_data_structures_and_algorithms/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

btree.py里面的preorder_trav_use_stack

alittlebitcool opened this issue · comments

里面插入的是不是应该为peek 而不是 subtree

hi, 是有问题的已经更新了 master。之前代码有两个问题:

  • 应该是 push peek 的 left 和 right,手误写了 subtree
  • 使用 stack 后进先出之后需要先 push right,再 push left 。
    def preorder_trav_use_stack(self, subtree):
        """递归的方式其实是计算机帮我们实现了栈结构,我们可以自己显示的用栈来实现"""
        s = Stack()
        if subtree:
            s.push(subtree)
            while not s.empty():
                top_node = s.pop()
                print(top_node.data)    # 注意这里我用了 print,你可以用 yield 产出值然后在调用的地方转成 list
                if top_node.right:
                    s.push(top_node.right)
                if top_node.left:
                    s.push(top_node.left)