更多代码: Gitee主页:https://gitee.com/GZHzzz
博客主页: CSDN:https://blog.csdn.net/gzhzzaa
二叉树遍历
- 树的遍历是树的一种重要的运算。所谓遍历是指对树中所有节点的信息的访问。即依次对树中每个结点访问一次且仅访问一次。我们把这种对所有节点的访问称为遍历(traveral)。那么树的两种重要的遍历模式是深度优先遍历和广度优先遍历,深度优先一般用递归,广度优先一般用队列。
深度优先遍历😎
-
对于一棵二叉树,深度优先搜索(Depth First Search)是沿着树的
深度
遍历树的节点,尽可能深的搜索树的分支。 -
深度遍历有重要的三种方法。这三种方法经常被用于访问树的节点,它们之间的不同在于访问每个节点的次序不同。这三种遍历分别是:先序遍历(preorder),中序遍历(inorder)和后序遍历(postorder)。
先序遍历 (根 - 左 - 右)
- 先访问根节点,然后递归使用先序遍历访问左子树,再递归使用先序遍历访问右子树。
def preorder(self,root):
'''递归实现先序遍历'''
if root == None: return
print root.elem
self.preorder(root.lchild)
self.preorder(root.rchild)
中序遍历 (左 - 根 - 右)
- 递归使用中序遍历访问左子树,然后访问根节点,最后再递归使用中序遍历访问右子树。
def preorder(self,root):
'''递归实现先序遍历'''
if root == None: return
self.preorder(root.lchild)
print root.elem
self.preorder(root.rchild)
后序遍历 (左 - 右 - 根)
- 先递归使用后序遍历访问左子树和右子树,最后访问根节点。
def preorder(self,root):
'''递归实现先序遍历'''
if root == None: return
self.preorder(root.lchild)
self.preorder(root.rchild)
print root.elem
广度优先遍历(BFS)
- 广度优先遍历(Breadth First Search),也称为层次遍历。从树的 root 开始,从上到下从左到右遍历整个树的节点。
- 通常用队列queue实现层序遍历
def breadth_travel(self,root):
'''利用队列实现树的层次遍历'''
if root == None: root
queue = []
queue.append(root)
while queue:
node = queue.pop(0)
print node.elem
if node.lchild != None:
queue.append(node.lchild)
if node.rchild != None:
queue.append(node.rchild)
- 前一层和下一层的节点都保存在queue中,按照从左到右的顺序!😝
写在最后
十年磨剑,与君共勉!
更多代码:Gitee主页:https://gitee.com/GZHzzz
博客主页:CSDN:https://blog.csdn.net/gzhzzaa
- Fighting!😎
while True:
Go life