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操作数据库之sqlite3打开数据库、删除、修改示例
Mar 13 Python
python中lambda函数 list comprehension 和 zip函数使用指南
Sep 28 Python
python将ip地址转换成整数的方法
Mar 17 Python
简单介绍使用Python解析并修改XML文档的方法
Oct 15 Python
Python中工作日类库Busines Holiday的介绍与使用
Jul 06 Python
Scrapy框架CrawlSpiders的介绍以及使用详解
Nov 29 Python
Python计算一个给定时间点前一个月和后一个月第一天的方法
May 29 Python
pygame游戏之旅 如何制作游戏障碍
Nov 20 Python
django使用django-apscheduler 实现定时任务的例子
Jul 20 Python
python 利用pywifi模块实现连接网络破解wifi密码实时监控网络
Sep 16 Python
Python3.9又更新了:dict内置新功能
Feb 28 Python
Django 解决distinct无法去除重复数据的问题
May 20 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使用header()输出图片缓存实例
2014/12/09 PHP
php foreach如何跳出两层循环(详解)
2016/11/05 PHP
PHP通过curl获取接口URL的数据方法
2018/05/31 PHP
PHP 文件上传限制问题
2019/09/01 PHP
jQuery EasyUI API 中文文档 - NumberSpinner数值微调器使用介绍
2011/10/21 Javascript
Knockoutjs的环境搭建教程
2012/11/26 Javascript
jQuery回车实现登录简单实现
2013/08/20 Javascript
jquery设置元素的readonly和disabled的写法
2013/09/22 Javascript
js读取注册表的键值示例
2013/09/25 Javascript
一行命令搞定node.js 版本升级
2014/07/20 Javascript
js编写一个简单的产品放大效果代码
2016/06/27 Javascript
JS中showModalDialog关闭子窗口刷新主窗口用法详解
2017/03/25 Javascript
js实现三级联动效果(简单易懂)
2017/03/27 Javascript
详解微信第三方小程序代开发
2017/06/23 Javascript
koa大型web项目中使用路由装饰器的方法示例
2019/04/02 Javascript
在微信小程序中渲染HTML内容3种解决方案及分析与问题解决
2020/01/12 Javascript
BootStrap前端框架使用方法详解
2020/02/26 Javascript
[01:04]DOTA2:伟大的Roshan雕塑震撼来临
2015/01/30 DOTA
[48:46]完美世界DOTA2联赛PWL S2 SZ vs FTD.C 第二场 11.19
2020/11/19 DOTA
用实例解释Python中的继承和多态的概念
2015/04/27 Python
Python匹配中文的正则表达式
2016/05/11 Python
详解python并发获取snmp信息及性能测试
2017/03/27 Python
python中字符串类型json操作的注意事项
2017/05/02 Python
15行Python代码带你轻松理解令牌桶算法
2018/03/21 Python
python 获取文件下所有文件或目录os.walk()的实例
2018/04/23 Python
Python实现二叉树前序、中序、后序及层次遍历示例代码
2019/05/18 Python
Python实现操纵控制windows注册表的方法分析
2019/05/24 Python
python SVM 线性分类模型的实现
2019/07/19 Python
html5 Web SQL Database 之事务处理函数transaction与executeSQL解析
2013/11/07 HTML / CSS
美国知名女性服饰品牌:New York & Company
2017/03/23 全球购物
爽歪歪广告词
2014/03/20 职场文书
青年文明号创建承诺
2014/03/31 职场文书
村党的群众路线教育实践活动总结材料
2014/10/31 职场文书
2014年青年教师工作总结
2014/12/17 职场文书
民主生活会意见
2015/06/05 职场文书
六年级作文之自救
2019/12/19 职场文书