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中if语句的嵌套用法
May 14 Python
Python用list或dict字段模式读取文件的方法
Jan 10 Python
浅谈Python中带_的变量或函数命名
Dec 04 Python
Python自定义线程池实现方法分析
Feb 07 Python
python如何在循环引用中管理内存
Mar 20 Python
对python中的pop函数和append函数详解
May 04 Python
详解Python函数式编程—高阶函数
Mar 29 Python
PyTorch基本数据类型(一)
May 22 Python
对Pytorch神经网络初始化kaiming分布详解
Aug 18 Python
Python彻底删除文件夹及其子文件方式
Dec 23 Python
Django Haystack 全文检索与关键词高亮的实现
Feb 17 Python
aws 通过boto3 python脚本打pach的实现方法
May 10 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下使用CURL方式POST数据至API接口的代码
2013/02/14 PHP
通过php添加xml文档内容的方法
2015/01/23 PHP
codeigniter发送邮件并打印调试信息的方法
2015/03/21 PHP
Yii2 rbac权限控制之菜单menu实例教程
2016/04/28 PHP
PHP使用pdo连接access数据库并循环显示数据操作示例
2018/06/05 PHP
PHP实现类似题库抽题效果
2018/08/16 PHP
PHP7 windows支持
2021/03/09 PHP
JS记录用户登录次数实现代码
2014/01/15 Javascript
js实现文本框中焦点在最后位置
2014/03/04 Javascript
Javascript学习笔记之函数篇(六) : 作用域与命名空间
2014/11/23 Javascript
JSON格式的键盘编码对照表
2015/01/29 Javascript
JS事件添加和移出的兼容写法示例
2016/06/20 Javascript
Vue表单验证插件Vue Validator使用方法详解
2017/04/07 Javascript
vue初尝试--项目结构(推荐)
2018/01/30 Javascript
vue2.0组件之间传值、通信的多种方式(干货)
2018/02/10 Javascript
vue element-ui 绑定@keyup事件无效的解决方法
2018/03/09 Javascript
element UI upload组件上传附件格式限制方法
2018/09/04 Javascript
[36:14]DOTA2上海特级锦标赛D组小组赛#1 EG VS COL第二局
2016/02/28 DOTA
python检查URL是否正常访问的小技巧
2017/02/25 Python
python列表的增删改查实例代码
2018/01/30 Python
python3中类的继承以及self和super的区别详解
2019/06/26 Python
Python3 文章标题关键字提取的例子
2019/08/26 Python
python matplotlib包图像配色方案分享
2020/03/14 Python
调整Jupyter notebook的启动目录操作
2020/04/10 Python
CSS3实现鼠标悬停显示扩展内容
2016/08/24 HTML / CSS
HTML5新增加标签和功能概述
2016/09/05 HTML / CSS
喝酒检查书范文
2014/02/23 职场文书
应聘编辑自荐信范文
2014/03/12 职场文书
环境工程专业自荐信范文
2014/06/24 职场文书
2015年科室工作总结
2015/04/10 职场文书
2015年大学学生会工作总结
2015/05/13 职场文书
大学生入党群众意见书
2015/06/02 职场文书
节水宣传标语口号
2015/12/26 职场文书
2016年优秀共青团员事迹材料
2016/02/25 职场文书
pytorch 如何把图像数据集进行划分成train,test和val
2021/05/31 Python
Python matplotlib 利用随机函数生成变化图形
2022/04/26 Python