Python实现二叉树结构与进行二叉树遍历的方法详解


Posted in Python onMay 24, 2016

二叉树的建立

Python实现二叉树结构与进行二叉树遍历的方法详解

使用类的形式定义二叉树,可读性更好

class BinaryTree:
  def __init__(self, root):
    self.key = root
    self.left_child = None
    self.right_child = None
  def insert_left(self, new_node):
    if self.left_child == None:
      self.left_child = BinaryTree(new_node)
    else:
      t = BinaryTree(new_node)
      t.left_child = self.left_child
      self.left_child = t
  def insert_right(self, new_node):
    if self.right_child == None:
      self.right_child = BinaryTree(new_node)
    else:
      t = BinaryTree(new_node)
      t.right_child = self.right_child
      self.right_child = t
  def get_right_child(self):
    return self.right_child
  def get_left_child(self):
    return self.left_child
  def set_root_val(self, obj):
    self.key = obj
  def get_root_val(self):
    return self.key

r = BinaryTree('a')
print(r.get_root_val())
print(r.get_left_child())
r.insert_left('b')
print(r.get_left_child())
print(r.get_left_child().get_root_val())
r.insert_right('c')
print(r.get_right_child())
print(r.get_right_child().get_root_val())
r.get_right_child().set_root_val('hello')
print(r.get_right_child().get_root_val())

Python进行二叉树遍历

需求:
python代码实现二叉树的:
1. 前序遍历,打印出遍历结果
2. 中序遍历,打印出遍历结果
3. 后序遍历,打印出遍历结果
4. 按树的level遍历,打印出遍历结果
5. 结点的下一层如果没有子节点,以‘N'代替

方法:
使用defaultdict或者namedtuple表示二叉树
使用StringIO方法,遍历时写入结果,最后打印出结果
打印结点值时,如果为空,StringIO()写入‘N '
采用递归访问子节点
代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# test tree as below:
''' 1 / \ / \ / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 N / \ / \ / \ 7 N N N 8 9 / \ / \ / \ N N N N N N '''

from collections import namedtuple
from io import StringIO

#define the node structure
Node = namedtuple('Node', ['data', 'left', 'right'])
#initialize the tree
tree = Node(1,
      Node(2,
         Node(4,
           Node(7, None, None),
           None),
         Node(5, None, None)),
      Node(3,
         Node(6,
           Node(8, None, None),
           Node(9, None, None)),
         None))
#read and write str in memory
output = StringIO()


#read the node and write the node's value
#if node is None, substitute with 'N '
def visitor(node):
  if node is not None:
    output.write('%i ' % node.data)
  else:
    output.write('N ')


#traversal the tree with different order
def traversal(node, order):
  if node is None:
    visitor(node)
  else:
    op = {
        'N': lambda: visitor(node),
        'L': lambda: traversal(node.left, order),
        'R': lambda: traversal(node.right, order),
    }
    for x in order:
      op[x]()


#traversal the tree level by level
def traversal_level_by_level(node):
  if node is not None:
    current_level = [node]
    while current_level:
      next_level = list()
      for n in current_level:
        if type(n) is str:
          output.write('N ')
        else:
          output.write('%i ' % n.data)
          if n.left is not None:
            next_level.append(n.left)
          else:
            next_level.append('N')
          if n.right is not None:
            next_level.append(n.right)
          else:
            next_level.append('N ')

      output.write('\n')
      current_level = next_level


if __name__ == '__main__':
  for order in ['NLR', 'LNR', 'LRN']:
    if order == 'NLR':
      output.write('this is preorder traversal:')
      traversal(tree, order)
      output.write('\n')
    elif order == 'LNR':
      output.write('this is inorder traversal:')
      traversal(tree, order)
      output.write('\n')
    else:
      output.write('this is postorder traversal:')
      traversal(tree, order)
      output.write('\n')

  output.write('traversal level by level as below:'+'\n')
  traversal_level_by_level(tree)

  print(output.getvalue())
Python 相关文章推荐
Django1.3添加app提示模块不存在的解决方法
Aug 26 Python
python获取文件后缀名及批量更新目录下文件后缀名的方法
Nov 11 Python
python避免死锁方法实例分析
Jun 04 Python
python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解
Oct 20 Python
Python栈算法的实现与简单应用示例
Nov 01 Python
python3实现域名查询和whois查询功能
Jun 21 Python
解决django后台样式丢失,css资源加载失败的问题
Jun 11 Python
Python使用sklearn实现的各种回归算法示例
Jul 04 Python
如何关掉pycharm中的python console(图解)
Oct 31 Python
Python 执行矩阵与线性代数运算
Aug 01 Python
Python Pandas模块实现数据的统计分析的方法
Jun 24 Python
手把手教你使用TensorFlow2实现RNN
Jul 15 Python
Python中set与frozenset方法和区别详解
May 23 #Python
python实现多线程的两种方式
May 22 #Python
python实现简单购物商城
May 21 #Python
python字符串的常用操作方法小结
May 21 #Python
python实现用户登录系统
May 21 #Python
python列表的常用操作方法小结
May 21 #Python
bat和python批量重命名文件的实现代码
May 19 #Python
You might like
PHP 日期加减的类,很不错
2009/10/10 PHP
Admin generator, filters and I18n
2011/10/06 PHP
PHP保存session到memcache服务器的方法
2016/01/19 PHP
PHP PDO数据库操作预处理与注意事项
2019/03/16 PHP
学习面向对象之面向对象的基本概念:对象和其他基本要素
2010/11/30 Javascript
js 数据类型转换总结笔记
2011/01/17 Javascript
JS中prototype关键字的功能介绍及使用示例
2013/07/21 Javascript
整理Javascript数组学习笔记
2015/11/29 Javascript
JavaScript简单获取系统当前时间完整示例
2016/08/02 Javascript
纯js和css完成贪吃蛇小游戏demo
2016/09/01 Javascript
详解vue.js2.0父组件点击触发子组件方法
2017/05/10 Javascript
微信小程序 选项卡的简单实例
2017/05/24 Javascript
JavaScript实现刮刮乐效果
2020/11/01 Javascript
[02:19]2014DOTA2国际邀请赛 专访820少年们一起去追梦吧
2014/07/14 DOTA
[49:20]VG vs TNC Supermajor小组赛B组败者组决赛 BO3 第二场 6.2
2018/06/03 DOTA
Python数据报表之Excel操作模块用法分析
2019/03/11 Python
pyqt5 lineEdit设置密码隐藏,删除lineEdit已输入的内容等属性方法
2019/06/24 Python
python opencv 读取图片 返回图片某像素点的b,g,r值的实现方法
2019/07/03 Python
在pytorch中查看可训练参数的例子
2019/08/18 Python
python判断链表是否有环的实例代码
2020/01/31 Python
Selenium环境变量配置(火狐浏览器)及验证实现
2020/12/07 Python
html5 application cache遇到的严重问题
2012/12/26 HTML / CSS
Fossil加拿大官网:化石手表、手袋、首饰及配饰
2019/04/23 全球购物
CheapTickets泰国:廉价航班,查看促销价格并预订机票
2019/12/28 全球购物
泰国第一在线超市:Tops
2021/02/13 全球购物
什么是SQL Server的确定性函数和不确定性函数
2016/08/04 面试题
EJB的几种类型
2012/08/15 面试题
晨会主持词
2014/03/17 职场文书
2014年加油站工作总结
2014/12/04 职场文书
超市督导岗位职责
2015/04/10 职场文书
尊师重教主题班会
2015/08/14 职场文书
大学学习委员竞选稿
2015/11/20 职场文书
2016优秀教师先进个人事迹材料
2016/02/25 职场文书
入党申请书怎么写?
2019/06/21 职场文书
MySQL数据迁移相关总结
2021/04/29 MySQL
Python使用永中文档转换服务
2022/05/06 Python