Python实现二叉树前序、中序、后序及层次遍历示例代码

yipeiwu_com6年前Python基础

前言

树是数据结构中非常重要的一种,主要的用途是用来提高查找效率,对于要重复查找的情况效果更佳,如二叉排序树、FP-树。另外可以用来提高编码效率,如哈弗曼树。

用 Python 实现树的构造和几种遍历算法。实现功能如下:

  • 树的构造
  • 递归实现先序遍历、中序遍历、后序遍历
  • 堆栈实现先序遍历、中序遍历、后序遍历
  • 队列实现层次遍历
# -*- coding=utf-8 -*-


class Node(object):
 """节点类"""

 def __init__(self, element=-1, l_child=None, r_child=None):
  self.element = element
  self.l_child = l_child
  self.r_child = r_child


class Tree(object):
 """树类"""

 def __init__(self):
  self.root = Node()
  self.queue = []

 def add_node(self, element):
  """为树添加节点"""

  node = Node(element)
  # 如果树是空的,则对根节点赋值
  if self.root.element == -1:
   self.root = node
   self.queue.append(self.root)
  else:
   tree_node = self.queue[0]
   # 此结点没有左子树,则创建左子树节点
   if tree_node.l_child is None:
    tree_node.l_child = node
    self.queue.append(tree_node.l_child)
   else:
    tree_node.r_child = node
    self.queue.append(tree_node.r_child)
    # 如果该结点存在右子树,将此节点丢弃
    self.queue.pop(0)

 def front_recursion(self, root):
  """利用递归实现树的前序遍历"""

  if root is None:
   return

  print root.element,
  self.front_recursion(root.l_child)
  self.front_recursion(root.r_child)

 def middle_recursion(self, root):
  """利用递归实现树的中序遍历"""

  if root is None:
   return

  self.middle_recursion(root.l_child)
  print root.element,
  self.middle_recursion(root.r_child)

 def back_recursion(self, root):
  """利用递归实现树的后序遍历"""

  if root is None:
   return

  self.back_recursion(root.l_child)
  self.back_recursion(root.r_child)
  print root.element,

 @staticmethod
 def front_stack(root):
  """利用堆栈实现树的前序遍历"""

  if root is None:
   return

  stack = []
  node = root
  while node or stack:
   # 从根节点开始,一直找它的左子树
   while node:
    print node.element,
    stack.append(node)
    node = node.l_child
   # while结束表示当前节点node为空,即前一个节点没有左子树了
   node = stack.pop()
   # 开始查看它的右子树
   node = node.r_child

 @staticmethod
 def middle_stack(root):
  """利用堆栈实现树的中序遍历"""

  if root is None:
   return

  stack = []
  node = root
  while node or stack:
   # 从根节点开始,一直找它的左子树
   while node:
    stack.append(node)
    node = node.l_child
   # while结束表示当前节点node为空,即前一个节点没有左子树了
   node = stack.pop()
   print node.element,
   # 开始查看它的右子树
   node = node.r_child

 @staticmethod
 def back_stack(root):
  """利用堆栈实现树的后序遍历"""

  if root is None:
   return

  stack1 = []
  stack2 = []
  node = root
  stack1.append(node)
  # 这个while循环的功能是找出后序遍历的逆序,存在stack2里面
  while stack1:
   node = stack1.pop()
   if node.l_child:
    stack1.append(node.l_child)
   if node.r_child:
    stack1.append(node.r_child)
   stack2.append(node)
  # 将stack2中的元素出栈,即为后序遍历次序
  while stack2:
   print stack2.pop().element,

 @staticmethod
 def level_queue(root):
  """利用队列实现树的层次遍历"""

  if root is None:
   return

  queue = []
  node = root
  queue.append(node)
  while queue:
   node = queue.pop(0)
   print node.element,
   if node.l_child is not None:
    queue.append(node.l_child)
   if node.r_child is not None:
    queue.append(node.r_child)


if __name__ == '__main__':
 """主函数"""

 # 生成十个数据作为树节点
 elements = range(10)
 tree = Tree()
 for elem in elements:
  tree.add_node(elem)

 print '队列实现层次遍历:'
 tree.level_queue(tree.root)

 print '\n\n递归实现前序遍历:'
 tree.front_recursion(tree.root)
 print '\n递归实现中序遍历:'
 tree.middle_recursion(tree.root)
 print '\n递归实现后序遍历:'
 tree.back_recursion(tree.root)

 print '\n\n堆栈实现前序遍历:'
 tree.front_stack(tree.root)
 print '\n堆栈实现中序遍历:'
 tree.middle_stack(tree.root)
 print '\n堆栈实现后序遍历:'
 tree.back_stack(tree.root)

需要源码的小伙伴可自行下载:代码传送门

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python回文字符串及回文数字判定功能示例

本文实例讲述了Python回文字符串及回文数字判定功能。分享给大家供大家参考,具体如下: 所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的。回文数字也是如此。 pyth...

Python中的pathlib.Path为什么不继承str详解

起步 既然所有路径都可以表示为字符串,为什么 pathlib.Path 不继承 str ? 这个想法的提出在 https://mail.python.org/pipermail...

20行python代码的入门级小游戏的详解

背景: 作为一个python小白,今天从菜鸟教程上看了一些python的教程,看到了python的一些语法,对比起来(有其他语言功底),感觉还是非常有趣,就随手添了一点内容,改了一个小例...

在python image 中安装中文字体的实现方法

如果一些应用需要到中文字体(如果pygraphviz,不安装中文字体,中文会显示乱码),就要在image 中安装中文字体。 默认 python image 是不包含中文字体的: ma...

Python实现计算长方形面积(带参数函数demo)

Python实现计算长方形面积(带参数函数demo)

如下所示: # 计算面积函数 def area(width, height): return width * height def print_welcome(name):...