二叉树深度优先遍历:先序遍历,中序遍历,后序遍历的递归与非递归。
二叉树广度优先遍历:层次遍历。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#递归前序
def preTran(head):
if head is not None:
print(head.val)
preTran(head.left)
preTran(head.right)
#递归中序
def midTran(head):
if head is not None:
midTran(head.left)
print(head.val)
midTran(head.right)
#递归后序
def postTran(head):
if head is not None:
postTran(head.left)
postTran(head.right)
print(head.val)
#非递归前序
def preTranStack(head):
if head is None:
return
p = head
stack = []
while p is not None or len(stack) > 0:
if p is not None:
print(p.val)
stack.append(p)
p = p.left
else:
p = stack.pop()
p = p.right
#非递归中序
def midTranStack(head):
if head is None:
return
p = head
stack = []
while p is not None or len(stack) > 0:
if p is not None:
stack.append(p)
p = p.left
else:
p = stack.pop()
print(p.val)
p = p.right
#非递归后序
def postTranStack(head):
if head is None:
return
cur = head
pre = None
stack = [cur]
while len(stack) > 0:
cur = stack[-1]
if (cur.left is None and cur.right is None) or (pre == cur.left) or (pre == cur.right):
cur = stack.pop()
print(cur.val)
pre = cur
else:
if cur.right is not None:
stack.append(cur.right)
if cur.left is not None:
stack.append(cur.left)
#广度优先,or层次遍历
def BFS(head):
p = head
queue = [p]
while len(queue) > 0:
p = queue.pop(0)
print(p.val)
if p.left is not None:
queue.append(p.left)
if p.right is not None:
queue.append(p.right)