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 相关文章推荐
python 实时遍历日志文件
Apr 12 Python
python使用电子邮件模块smtplib的方法
Aug 28 Python
python 网络编程详解及简单实例
Apr 25 Python
对Python 数组的切片操作详解
Jul 02 Python
Django页面数据的缓存与使用的具体方法
Apr 23 Python
python matplotlib画盒图、子图解决坐标轴标签重叠的问题
Jan 19 Python
利用python实现凯撒密码加解密功能
Mar 31 Python
Python如何获取文件指定行的内容
May 27 Python
在keras里面实现计算f1-score的代码
Jun 15 Python
Keras 在fit_generator训练方式中加入图像random_crop操作
Jul 03 Python
python 监控logcat关键字功能
Sep 04 Python
OpenCV实现机器人对物体进行移动跟随的方法实例
Nov 09 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
在DC的漫画和电影中,蝙蝠侠的宿敌,小丑的真名是什么?
2020/04/09 欧美动漫
轻松修复Discuz!数据库
2008/05/03 PHP
PHP伪静态写法附代码
2008/06/20 PHP
php 学习资料零碎东西
2010/12/04 PHP
php中使用Imagick实现图像直方图的实现代码
2011/08/30 PHP
php无限遍历目录示例
2014/02/21 PHP
php统计文章排行示例
2014/03/04 PHP
PHP使用缓存即时输出内容(output buffering)的方法
2015/08/03 PHP
php实现的简单中文验证码功能示例
2017/01/03 PHP
PHP观察者模式示例【Laravel框架中有用到】
2018/06/15 PHP
Laravel框架控制器,视图及模型操作图文详解
2019/12/04 PHP
jquery 表单进行客户端验证demo
2009/08/24 Javascript
jQuery的Ajax时无响应数据的解决方法
2010/05/25 Javascript
Node.js静态文件服务器改进版
2016/01/10 Javascript
详解JavaScript时间处理之几个月前或几个月后的指定日期
2016/12/21 Javascript
从零开始学习Node.js系列教程之SQLite3和MongoDB用法分析
2017/04/13 Javascript
JavaScript面向对象精要(下部)
2017/09/12 Javascript
浅谈React中的元素、组件、实例和节点
2018/02/27 Javascript
详解React Native 屏幕适配(炒鸡简单的方法)
2018/06/11 Javascript
微信小程序当前时间时段选择器插件使用方法详解
2018/12/28 Javascript
javascript canvas时钟模拟器
2020/07/13 Javascript
[05:28]刀塔密之一:团结则存
2014/07/03 DOTA
在Python中利用Into包整洁地进行数据迁移的教程
2015/03/30 Python
python中字符串变二维数组的实例讲解
2018/04/03 Python
详解将Django部署到Centos7全攻略
2018/09/26 Python
Python解析命令行读取参数之argparse模块
2019/07/26 Python
pytorch掉坑记录:model.eval的作用说明
2020/06/23 Python
Python 实现将某一列设置为str类型
2020/07/14 Python
css3 按钮 利用css3实现超酷下载按钮
2013/03/18 HTML / CSS
深入剖析webstorage[html5的本地数据处理]
2016/07/11 HTML / CSS
优秀女职工事迹材料
2014/02/06 职场文书
2014年文学毕业生自我鉴定
2014/04/23 职场文书
关于感恩的素材句子(38句)
2019/11/11 职场文书
Jsonp劫持学习
2021/04/01 PHP
nginx中proxy_pass各种用法详解
2021/11/07 Servers
在NumPy中深拷贝和浅拷贝相关操作的定义和背后的原理
2022/04/14 Python