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 14 Python
python安装以及IDE的配置教程
Apr 29 Python
详解python调度框架APScheduler使用
Mar 28 Python
python算法表示概念扫盲教程
Apr 13 Python
python实现感知器
Dec 19 Python
python PyTorch预训练示例
Feb 11 Python
TensorFlow实现非线性支持向量机的实现方法
Apr 28 Python
linux查找当前python解释器的位置方法
Feb 20 Python
如何基于Python创建目录文件夹
Dec 31 Python
PyTorch使用cpu加载模型运算方式
Jan 13 Python
python 如何快速复制序列
Sep 07 Python
解决pytorch 损失函数中输入输出不匹配的问题
Jun 05 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
给apache2.2加上mod_encoding模块後 php5.2.0 处理url出现bug
2007/04/12 PHP
PHP网页游戏学习之Xnova(ogame)源码解读(五)
2014/06/23 PHP
Yii编程开发常见调用技巧集锦
2016/07/15 PHP
Thinkphp 框架扩展之Widget扩展实现方法分析
2020/04/23 PHP
找到一点可怜的关于dojo资料,谢谢作者!
2006/12/06 Javascript
JavaScript 不只是脚本
2007/05/30 Javascript
window.js 主要包含了页面的一些操作
2009/12/23 Javascript
php is_numberic函数造成的SQL注入漏洞
2014/03/10 Javascript
JavaScript实现找出字符串中第一个不重复的字符
2014/09/03 Javascript
使用JS+plupload直接批量上传图片到又拍云
2014/12/01 Javascript
Vue.js 父子组件通讯开发实例
2016/09/06 Javascript
Jquery根据浏览器窗口改变调整大小的方法
2017/02/07 Javascript
elemetUi 组件--el-upload实现上传Excel文件的实例
2017/10/27 Javascript
React Native中导航组件react-navigation跨tab路由处理详解
2017/10/31 Javascript
详解关于webpack多入口热加载很慢的原因
2019/04/24 Javascript
Node.js爬虫如何获取天气和每日问候详解
2019/08/26 Javascript
解决vue语法会有延迟加载显现{{xxx}}的问题
2019/11/14 Javascript
基于jsbarcode 生成条形码并将生成的条码保存至本地+源码
2020/04/27 Javascript
vue tab切换,解决echartst图表宽度只有100px的问题
2020/07/19 Javascript
[01:01:42]Secret vs Optic Supermajor 胜者组 BO3 第二场 6.4
2018/06/05 DOTA
Python的高级Git库 Gittle
2014/09/22 Python
python中的多重继承实例讲解
2014/09/28 Python
在python中实现强制关闭线程的示例
2019/01/22 Python
关于Flask项目无法使用公网IP访问的解决方式
2019/11/19 Python
Python如何通过Flask-Mail发送电子邮件
2020/01/29 Python
Python 实现将大图切片成小图,将小图组合成大图的例子
2020/03/14 Python
浅谈Python中的生成器和迭代器
2020/06/19 Python
PyCharm 2020.2 安装详细教程
2020/09/25 Python
Numpy中的数组搜索中np.where方法详细介绍
2021/01/08 Python
德国电子商城:ComputerUniverse
2017/04/21 全球购物
求高于平均分的学生学号及成绩
2016/09/01 面试题
升职自荐信范文
2013/10/05 职场文书
基层工作经历证明
2014/01/13 职场文书
文明倡议书范文
2014/04/15 职场文书
幼儿园教师师德师风演讲稿:我自豪我是一名幼师
2014/09/10 职场文书
MySQL系列之五 视图、存储函数、存储过程、触发器
2021/07/02 MySQL