首先想到是递归算法,写法简单;二叉树的非递归算法需要用到辅助栈
二叉树结构定义
class BinNode():
def __init__( self, val ):
self.lchild = None
self.rchild = None
self.val = val
前序遍历
递归写法
def preOrder(self,root):
if not root:
return None
print(root.val)
self.preOrder(root.left)
self.preOrder(root.right)
非递归写法
preOrder每次都将遇到的节点压入栈,
- 当左子树遍历完毕后才从栈中弹出最后一个访问的节点,访问其右子树。
- 在同一层中,不可能同时有两个节点压入栈,因此栈的空间大小为O(h),h为二叉树高度。
- 时间方面,每个节点都被压入栈一次,弹出栈一次,访问一次,复杂度为O(n),n为节点个数。
def preOrder(self, root):
if not root:
return None
stack = []
node = root
while node or stack:
# 递归遍历当前节点与节点的左二子
while node:
stack.append(node)
print node.val
node = node.left
# while结束表示当前节点node为空,即前一个节点没有左子树了
# 弹出已访问的元素,下一轮循环访问其右节点
node = stack.pop()
node = node.right
中序遍历
递归写法
def inOrder(self,root):
if not root:
return None
self.inOrder(root.left)
print(root.val)
self.inOrder(root.right)
非递归写法
inOrder与preOrder需要调换一下节点访问的次序,
- 先序是先访问,再入栈;而中序则是先入栈,弹栈后再访问。
- 时间复杂度与空间复杂度同先序一致。
- 在同一层中,不可能同时有两个节点压入栈,因此栈的空间大小为O(h),h为二叉树高度。
- 时间方面,每个节点都被压入栈一次,弹出栈一次,访问一次,复杂度为O(n),n为节点个数。
def inOrder(self, root):
if not root:
return None
stack = []
node = root
while node or stack:
# 递归遍历当前节点与节点的左二子
while node:
stack.append(node)
node = node.left
# while结束表示当前节点node为空,即前一个节点没有左子树了
# 弹出已访问的元素,下一轮循环访问其右节点
node = stack.pop()
print node.val
node = node.right
后序遍历
递归写法
def postOrder(self,root):
if not root:
return None
self.inOrder(root.left)
self.inOrder(root.right)
print(root.val)
非递归写法
从直觉上来说,后序遍历对比中序遍历难度要增大很多。因为中序遍历节点序列有一点的连续性,而后续遍历则感觉有一定的跳跃性。
- 先左,再右,最后才中间节点;
- 访问左子树后,需要跳转到右子树,右子树访问完毕了再回溯至根节点并访问之。
- 解决思路:找出后序遍历的逆序,存在myStack2里面。
def postOrder(self, root):
if not root:
return []
stack1 = [root]
stack2 = []
node = root
while stack1:
node = stack1.pop()
# 使用while循环,将后序遍历的逆序结果,存入stack2
if node.left:
stack1.append(node.left)
if node.right:
stack1.append(node.right)
stack2.append(node)
while myStack2:
# 将myStack2中的元素出栈,即为后序遍历次序
print myStack2.pop().val