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 相关文章推荐
pygame实现弹力球及其变速效果
Jul 03 Python
Python 将RGB图像转换为Pytho灰度图像的实例
Nov 14 Python
python的numpy模块安装不成功简单解决方法总结
Dec 23 Python
Python实现PS滤镜的万花筒效果示例
Jan 23 Python
Python实现PS图像抽象画风效果的方法
Jan 23 Python
python list元素为tuple时的排序方法
Apr 18 Python
Python读取txt文件数据的方法(用于接口自动化参数化数据)
Jun 27 Python
Python空间数据处理之GDAL读写遥感图像
Aug 01 Python
Django中的静态文件管理过程解析
Aug 01 Python
Python引入多个模块及包的概念过程解析
Sep 21 Python
python 装饰器重要在哪
Feb 14 Python
python3 字符串str和bytes相互转换
Mar 23 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
第4章 数据处理-php数组的处理-郑阿奇
2011/07/04 PHP
php数组相加 array(“a”)+array(“b”)结果还是array(“a”)
2012/09/19 PHP
PHP框架Laravel中使用UUID实现数据分表操作示例
2018/05/30 PHP
php5.6.x到php7.0.x特性小结
2019/08/17 PHP
PHP与Web页面的交互示例详解一
2020/08/04 PHP
Using the TextRange Object
2006/10/14 Javascript
JS应用正则表达式转换大小写示例
2014/09/18 Javascript
使用HTML5+Boostrap打造简单的音乐播放器
2016/08/05 Javascript
BootStrap与validator 使用笔记(JAVA SpringMVC实现)
2016/09/21 Javascript
微信小程序  action-sheet详解及实例代码
2016/11/09 Javascript
基于jQuery实现表格的排序
2016/12/02 Javascript
Bootstrap CSS组件之输入框组
2016/12/17 Javascript
原生js实现简单的Ripple按钮实例代码
2017/03/24 Javascript
详解vue-cli中配置sass
2017/06/21 Javascript
JS对象序列化成json数据和json数据转化为JS对象的代码
2017/08/23 Javascript
一文让你彻底搞清楚javascript中的require、import与export
2017/09/24 Javascript
简化vuex的状态管理方案的方法
2018/06/02 Javascript
对angularJs中自定义指令replace的属性详解
2018/10/09 Javascript
详解javascript 变量提升(Hoisting)
2019/03/12 Javascript
详解微信小程序图片地扯转base64解决方案
2019/08/18 Javascript
VUEX-action可以修改state吗
2019/11/19 Javascript
js实现div色块拖动录制
2020/01/16 Javascript
[48:53]2014 DOTA2华西杯精英邀请赛 5 25 LGD VS VG第一场
2014/05/26 DOTA
Python使用设计模式中的责任链模式与迭代器模式的示例
2016/03/02 Python
python中从str中提取元素到list以及将list转换为str的方法
2018/06/26 Python
python抖音表白程序源代码
2019/04/07 Python
Python Pandas中根据列的值选取多行数据
2019/07/08 Python
移动端rem布局的两种实现方法
2018/01/03 HTML / CSS
CSS3中的@keyframes关键帧动画的选择器绑定
2016/06/13 HTML / CSS
解析html5 canvas实现背景鼠标连线动态效果代码
2019/06/17 HTML / CSS
全球精选男装和家居用品:Article
2020/04/13 全球购物
语文教育专业应届生求职信
2013/11/23 职场文书
本科生求职信
2014/06/17 职场文书
工厂仓管员岗位职责范本
2014/07/17 职场文书
四风对照检查材料思想汇报
2014/09/20 职场文书
幼儿园大班个人总结
2015/02/28 职场文书