二叉树的遍历非递归实现

二叉树的遍历非递归实现

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

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

代码:

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()

猜你喜欢

转载自www.cnblogs.com/yang-he/p/11411961.html