你看到的是今天的我,昨天的我已经死了

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

二叉树的遍历非递归实现

二叉树的遍历非递归实现

二叉树的非递归遍历使用栈来实现

  • 由于才用先跟序,遇到节点就应该访问,下一步应该沿着该树的左支下行。
  • 但节点的又支还没有访问,因此需要记录,将又节点压入栈中。
  • 遇到空树就溯回,取出栈中的一个又分支,像一颗二叉树一样遍历它。

代码:

1 def preorder(t, proc):
2     s = Stack()
3     while t is not None or s not s.is_empty():
4         while t is not None:
5             proc(t.data)
6             if t.right:
7                 s.push(t.right)
8             t = t.left
9         t = s.pop()

 通过生成器函数遍历

用Python写程序时,在考虑数据汇集结构的时候,总应该想到迭代器。下面是一个非递归实现的二叉树先序遍历迭代器:

1 def preorder(t):
2     s = Stack()
3     while t is not None or not s.is_empty():
4         while t is not None:
5             if t.right:
6                 s.push(t.right)
7             yield t.data
8             t = t.left
9         t = s.pop()

 

posted on 2019-08-26 13:13  橘子味的猫啊  阅读(139)  评论(0编辑  收藏  举报

导航