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 专题三 字符串的基础知识
Mar 19 Python
python算法表示概念扫盲教程
Apr 13 Python
pandas groupby 分组取每组的前几行记录方法
Apr 20 Python
解决新django中的path不能使用正则表达式的问题
Dec 18 Python
Python实现钉钉发送报警消息的方法
Feb 20 Python
Opencv+Python实现图像运动模糊和高斯模糊的示例
Apr 11 Python
python Elasticsearch索引建立和数据的上传详解
Aug 04 Python
python实现单链表的方法示例
Sep 03 Python
详解python statistics模块及函数用法
Oct 27 Python
python实现遍历文件夹图片并重命名
Mar 23 Python
Python实现AI换脸功能
Apr 10 Python
Python3如何使用tabulate打印数据
Sep 25 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 选项及相关信息函数库
2006/12/04 PHP
PHP 字符串编码截取函数(兼容utf-8和gb2312)
2009/05/02 PHP
php性能优化分析工具XDebug 大型网站调试工具
2011/05/22 PHP
php引用地址改变变量值的问题
2012/03/23 PHP
thinkPHP微信分享接口JSSDK用法实例
2017/07/07 PHP
PHP获取远程http或ftp文件的md5值的方法
2019/04/15 PHP
各种效果的jquery ui(接口)介绍
2008/09/17 Javascript
基于JQuery框架的AJAX实例代码
2009/11/03 Javascript
IE6,IE7下js动态加载图片不显示错误
2010/07/17 Javascript
小试JQuery的AutoComplete插件
2011/05/04 Javascript
namespace.js Javascript的命名空间库
2011/10/11 Javascript
jQuery操作checkbox选择(list/table)
2013/04/07 Javascript
JS打字效果的动态菜单代码分享
2015/08/21 Javascript
JavaScript获取当前运行脚本文件所在目录的方法
2016/02/03 Javascript
基于JS实现无缝滚动思路及代码分享
2016/06/07 Javascript
onmouseover事件和onmouseout事件全面理解
2016/08/15 Javascript
解决Vue 浏览器后退无法触发beforeRouteLeave的问题
2017/12/24 Javascript
浅谈react-router HashRouter和BrowserRouter的使用
2017/12/29 Javascript
微信小程序模版渲染详解
2018/01/26 Javascript
vue项目中跳转到外部链接的实例讲解
2018/09/20 Javascript
KOA+egg.js集成kafka消息队列的示例
2018/11/09 Javascript
发布Angular应用至生产环境的方法
2018/12/10 Javascript
微信小程序实现滑动切换自定义页码的方法分析
2018/12/29 Javascript
electron-vue利用webpack打包实现多页面的入口文件问题
2019/05/12 Javascript
JavaScript实现拖拽功能
2020/02/11 Javascript
解决vue-router 嵌套路由没反应的问题
2020/09/22 Javascript
Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法
2018/03/13 Python
基于python的多进程共享变量正确打开方式
2018/04/28 Python
python在地图上画比例的实例详解
2020/11/13 Python
python 将Excel转Word的示例
2021/03/02 Python
如何找出EMP表里面SALARY第N高的employee
2013/12/05 面试题
在DELPHI中调用存储过程和使用内嵌SQL哪种方式更好
2016/11/22 面试题
捐书活动总结
2014/05/04 职场文书
新闻人物通讯稿
2014/10/09 职场文书
年终奖金发放管理制度,中小企业适用,拿去救急吧!
2019/07/12 职场文书
Python文件的操作示例的详细讲解
2021/04/08 Python