二叉树的遍历【Python】

⼆叉树的遍历

树的遍历是树的⼀种重要的运算。所谓遍历是指对树中所有结点的信息的访问,即依次对树中每个结点访问⼀次且仅访问⼀次,我们把这种对所有节点的访问称为遍历(traversal)。
那么树的两种重要的遍历模式是深度优先遍历,⼴度优先遍历,深度优先⼀般⽤递归,⼴度优先⼀般⽤队列。⼀般情况下能⽤递归实现的算法⼤部分也能⽤堆栈来实现。

深度优先遍历

对于⼀颗⼆叉树,深度优先搜索(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 inorder(self, root):
		"""递归实现中序遍历"""
		if root == None:
			return
		self.inorder(root.lchild)
		print root.elem
		self.inorder(root.rchild)

后序遍历

在后序遍历中,我们先递归使⽤后序遍历访问左⼦树和右⼦树,最后访问根节点 。左⼦树->右⼦树->根节点

扫描二维码关注公众号,回复: 4985985 查看本文章
def postorder(self, root):
		"""递归实现后续遍历"""
		if root == None:
			return
		self.postorder(root.lchild)
		self.postorder(root.rchild)
		print root.elem

在这里插入图片描述
在这里插入图片描述

结果:
先序:a b c d e f g h
中序:b d c e a f h g
后序:d e c b h g f a

⼴度优先遍历(层次遍历)

从树的root开始,从上到下从从左到右遍历整个树的节点

def breadth_travel(self):
		"""利⽤队列实现树的层次遍历"""
		if root == None:
			return
		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)

猜你喜欢

转载自blog.csdn.net/weixin_38819889/article/details/85044141