入门小菜鸟,希望像做笔记记录自己学的东西,也希望能帮助到同样入门的人,更希望大佬们帮忙纠错啦~侵权立删。
目录
一、遍历的分类
1、深度遍历
沿着树的深度遍历树的节点,尽可能深的搜索树的分支。
其中先序遍历,中序遍历,后序遍历属于深度遍历,一般用用递归来实现。
先序遍历
若二叉树为空,为空操作;
否则(1)访问根节点;(2)先序遍历左子树;(3)先序遍历右子树。
以下图为例:
先序遍历为:1,2,3,5,4,6,7,8,9
中序遍历
若二叉树为空,为空操作;
否则(1)中序遍历左子树;(2)访问根结点;(3)中序遍历右子树。
同样的以此为例:
中序遍历为:5,3,2,4,1,9,8,6,7
后序遍历
若二叉树为空,为空操作;
否则(1)后序遍历左子树;(2)后序遍历右子树;(3)访问根结点。
同样的以此为例:
后序遍历为:5,3,4,2,9,8,7,6,1
2、广度遍历
从树的根层级开始一层一层的遍历,遍历完上一层再遍历下一层。
而层序遍历则属于广度遍历,一般用队列来实现。
层序遍历
若二叉树为空,为空操作;
否则从上到下、从左到右按层次进行访问。
同样的以此为例:
层序遍历为:1,2,6,3,4,7,8,5,9
二、python实现二叉树先序遍历
利用递归实现
def preorder(self,root): #先序遍历
if not root:
return
else:
print(root.data)
self.preorder(root.lchild)
self.preorder(root.rchild)
三、python实现二叉树中序遍历
def inorder(self, root): #中序遍历
if not root:
return
self.inorder(root.lchild)
print(root.data)
self.inorder(root.rchild)
四、python实现二叉树后序遍历
def nextorder(self,root): #后序遍历
if not root:
return
self.nextorder(root.lchild)
self.nextorder(root.rchild)
print(root.data)
五、python实现二叉树层序遍历
其实这个就是我们上一篇介绍的printtree()
def printtree(self): #输出整棵树(层序遍历)
if self.isEmpty():
return None
else:
queue = [self.root]
while queue:
cur = queue.pop(0)
print(cur.data)
if cur.lchild and cur.rchild:
queue.append(cur.lchild)
queue.append(cur.rchild)
elif not cur.lchild and cur.rchild:
queue.append(cur.rchild)
elif not cur.rchild and cur.lchild:
queue.append(cur.lchild)
六、具体调用
k.printtree()
k.preorder(k.root)
k.inorder(k.root)
k.nextorder(k.root)
欢迎大家在评论区批评指正,谢谢大家~