二叉树的前,中,后,层次遍历
递归版本的前序遍历
def preOrderRecur(node):
if not node:
return
print(node.val)
preOrderRecur(node.left)
preOrderRecur(node.right)
递归版本的中序遍历
def inOrderRecur(node):
if not node:
return
inOrderRecur(node.left)
print(node.val)
inOrderRecur(node.right)
递归版本的后序遍历
def postOrderRecur(node):
if not node:
return
postOrderRecur(node.left)
postOrderRecur(node.right)
print(node.val)
非递归版本的前序遍历
弹出即存,利用栈的特性优先遍历左子树
def preOrderStack(node):
if not node:
return
stack = [node]
res = []
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return res
非递归版本的中序遍历
def inOrderStack(node):
if not node:
return
stack = []
res = []
cur = node
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
非递归版本的后序遍历
def postOrderStack(node):
if not node:
return
stack = [node]
res = []
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
return res[::-1]
层次遍历
def levelOrder(node):
if not root:
return
queue = [node]
res = []
while queue:
cur = queue.pop(0)
res.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return res