二叉树的遍历
树的遍历是一种重要的运算。所谓遍历是指对树中所有节点信息的访问,即一次对树中每个接地访问一次且仅访问一次,将这种对所有节点的访问称为遍历(travelsal)。
树的两种重要遍历模式是深度优先遍历(DFS)和广度优先遍历(BFS),BFS 一般用遍历,DFS一般用队列。一般情况下能用递归实现的算法大部分也可以用堆栈实现。
广度优先遍历(层次遍历)
从树的root开始,实现上图所示的广度优先遍历(从上到下从左到右遍历整个树的节点)以及深度优先遍历(递归式先序、中序、后序),图右侧为遍历结果。
【示例】二叉树节点与树的建立
class Node(object):
def __init__(self, elem, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class Tree(object):
def __init__(self, root=None):
self.root = root
def add(self, elem):
node = Node(elem)
if self.root == None:
self.root = node
else:
queue = []
queue.append(self.root)
while queue:
cur = queue.pop(0)
if cur.lchild == None:
cur.lchild = node
return
elif cur.rchild == None:
cur.rchild = node
return
else:
queue.append(cur.lchild)
queue.append(cur.rchild)
【示例】广度优先遍历
def bfs(self):
if self.root == None:
return
else:
queue = []
queue.append(self.root)
while queue:
curNode = queue.pop(0)
print(curNode.elem, end='\t')
if curNode.lchild != None:
queue.append(curNode.lchild)
if curNode.rchild != None:
queue.append(curNode.rchild)
【示例】深度优先遍历——先序遍历(根->左->右)
#先序遍历,遍历方向:根->左->右
def preOrder(self, root):
if root is None:
return
else:
print(root.elem, end='\t')
self.preOrder(root.lchild)
self.preOrder(root.rchild)
【示例】深度优先遍历——中序遍历(左->根->右)
#中序遍历 遍历反向:左->根->右
def inOrder(self, root):
if root is None:
return
else:
self.inOrder(root.lchild)
print(root.elem, end='\t')
self.inOrder(root.rchild)
【示例】深度优先遍历——后序遍历(左->右->根)
#中序遍历 遍历方向:左->右->根
def lastOrder(self, root):
if root is None:
return
else:
self.lastOrder(root.lchild)
self.lastOrder(root.rchild)
print(root.elem, end='\t')
测试结果