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统计一个文本中重复行数的方法
Nov 19 Python
在Python中处理列表之reverse()方法的使用教程
May 21 Python
Django日志模块logging的配置详解
Feb 14 Python
python+selenium开发环境搭建图文教程
Aug 11 Python
用python制作游戏外挂
Jan 04 Python
Python+matplotlib实现计算两个信号的交叉谱密度实例
Jan 08 Python
Python面向对象程序设计之私有属性及私有方法示例
Apr 08 Python
在Pandas中处理NaN值的方法
Jun 25 Python
Pandas0.25来了千万别错过这10大好用的新功能
Aug 07 Python
利用python计算时间差(返回天数)
Sep 07 Python
Python读取表格类型文件代码实例
Feb 17 Python
python GUI库图形界面开发之PyQt5结合Qt Designer创建信号与槽的详细方法与实例
Mar 08 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 escape URL编码
2008/12/10 PHP
php mssql 数据库分页SQL语句
2008/12/16 PHP
PHPMYADMIN 简明安装教程 推荐
2010/03/07 PHP
php类中private属性继承问题分析
2012/11/01 PHP
PHP SPL标准库之数据结构堆(SplHeap)简单使用实例
2015/05/12 PHP
prettify 代码高亮着色器google出品
2010/12/28 Javascript
JavaScript前端图片加载管理器imagepool使用详解
2014/12/29 Javascript
localResizeIMG先压缩后使用ajax无刷新上传(移动端)
2015/08/11 Javascript
javascript引用类型之时间Date和数组Array
2015/08/27 Javascript
javascript中checkbox使用方法简单实例演示
2015/11/17 Javascript
Jquery 1.9.1源码分析系列(十二)之筛选操作
2015/12/02 Javascript
如何利用AngularJS打造一款简单Web应用
2015/12/05 Javascript
Vue.js每天必学之数据双向绑定
2016/09/05 Javascript
js实现常见的工具条效果
2017/03/02 Javascript
jQuery Validate 校验多个相同name的方法
2017/05/18 jQuery
javascript中mouseenter与mouseover的异同
2017/06/06 Javascript
node.js的Express服务器基本使用教程
2019/01/09 Javascript
VUE前后端学习tab写法实例
2019/08/06 Javascript
Python计算回文数的方法
2015/03/11 Python
Python自定义进程池实例分析【生产者、消费者模型问题】
2016/09/19 Python
python实现m3u8格式转换为mp4视频格式
2018/02/28 Python
Python变量赋值的秘密分享
2018/04/03 Python
Python中的异常处理try/except/finally/raise用法分析
2019/02/28 Python
详解python读取image
2019/04/03 Python
Python 的AES加密与解密实现
2019/07/09 Python
python datetime时间格式的相互转换问题
2020/06/11 Python
利用CSS3伪元素实现逐渐发光的方格边框
2017/05/07 HTML / CSS
CSS3动画特效在活动页中的应用
2020/01/21 HTML / CSS
HTML5表格_动力节点Java学院整理
2017/07/11 HTML / CSS
中国跨境电商:Tomtop
2017/03/16 全球购物
《三顾茅庐》教学反思
2014/04/10 职场文书
航空学院求职信
2014/06/11 职场文书
2014年保密工作总结
2014/11/22 职场文书
大学宣传委员竞选稿
2015/11/19 职场文书
2016年教代会开幕词
2016/03/04 职场文书
MySQL表的增删改查基础教程
2021/04/07 MySQL