python使用递归的方式建立二叉树


Posted in Python onJuly 03, 2019

树和图的数据结构,就很有意思啦。

python使用递归的方式建立二叉树

# coding = utf-8

 

 

class BinaryTree:

  def __init__(self, root_obj):

    self.key = root_obj

    self.left_child = None

    self.right_child = None

 

  def insert_left(self, new_node):

    node = BinaryTree(new_node)

    if self.left_child is None:

      self.left_child = node

    else:

      node.left_child = self.left_child

      self.left_child = node

 

  def insert_right(self, new_node):

    node = BinaryTree(new_node)

    if self.right_child is None:

      self.right_child = node

    else:

      node.right_child = self.right_child

      self.right_child = node

 

  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

 

 

root = BinaryTree('a')

print(root.get_root_val())

print(root.get_left_child())

root.insert_left('b')

print(root.get_left_child())

print(root.get_left_child().get_root_val())

root.insert_right('c')

print(root.get_right_child())

print(root.get_right_child().get_root_val())

root.get_right_child().set_root_val('hello')

print(root.get_right_child().get_root_val())
C:\Users\Sahara\.virtualenvs\test\Scripts\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py

a

None

<__main__.BinaryTree object at 0x00000000024139B0>

b

<__main__.BinaryTree object at 0x00000000024139E8>

c

hello

 

Process finished with exit code 0

Python实现二叉树遍历的递归和非递归算法

前序遍历

# -----------前序遍历 ------------
  # 递归算法
  def pre_order_recursive(self, T):
    if T == None:
      return
    print(T.root, end=' ')
    self.pre_order_recursive(T.lchild)
    self.pre_order_recursive(T.rchild)

  # 非递归算法
  def pre_order_non_recursive(self, T):
    """借助栈实现前驱遍历
    """
    if T == None:
      return
    stack = []
    while T or len(stack) > 0:
      if T:
        stack.append(T)
        print(T.root, end=' ')
        T = T.lchild
      else:
        T = stack[-1]
        stack.pop()
        T = T.rchild

中序遍历

# -----------中序遍历 ------------
  # 递归算法
  def mid_order_recursive(self, T):
    if T == None:
      return
    self.mid_order_recursive(T.lchild)
    print(T.root, end=' ')
    self.mid_order_recursive(T.rchild)

  # 非递归算法
  def mid_order_non_recursive(self, T):
    """借助栈实现中序遍历
    """
    if T == None:
      return
    stack = []
    while T or len(stack) > 0:
      if T:
        stack.append(T)
        T = T.lchild
      else:
        T = stack.pop()
        print(T.root, end=' ')
        T = T.rchild

后序遍历

# -----------后序遍历 ------------
  # 递归算法
  def post_order_recursive(self, T):
    if T == None:
      return
    self.post_order_recursive(T.lchild)
    self.post_order_recursive(T.rchild)
    print(T.root, end=' ')

  # 非递归算法
  def post_order_non_recursive(self, T):
    """借助两个栈实现后序遍历
    """
    if T == None:
      return
    stack1 = []
    stack2 = []
    stack1.append(T)
    while stack1:
      node = stack1.pop()
      if node.lchild:
        stack1.append(node.lchild)
      if node.rchild:
        stack1.append(node.rchild)
      stack2.append(node)
    while stack2:
      print(stack2.pop().root, end=' ')
    return

层次遍历

# -----------层次遍历 ------------
  def level_order(self, T):
    """借助队列(其实还是一个栈)实现层次遍历
    """
    if T == None:
      return
    stack = []
    stack.append(T)
    while stack:
      node = stack.pop(0) # 实现先进先出
      print(node.root, end=' ')
      if node.lchild:
        stack.append(node.lchild)
      if node.rchild:
        stack.append(node.rchild)

完整代码

class NodeTree:
  def __init__(self, root=None, lchild=None, rchild=None):
    """创建二叉树
    Argument:
      lchild: BinTree
        左子树
      rchild: BinTree
        右子树

    Return:
      Tree
    """
    self.root = root
    self.lchild = lchild
    self.rchild = rchild


class BinTree:

  # -----------前序遍历 ------------
  # 递归算法
  def pre_order_recursive(self, T):
    if T == None:
      return
    print(T.root, end=' ')
    self.pre_order_recursive(T.lchild)
    self.pre_order_recursive(T.rchild)

  # 非递归算法
  def pre_order_non_recursive(self, T):
    """借助栈实现前驱遍历
    """
    if T == None:
      return
    stack = []
    while T or len(stack) > 0:
      if T:
        stack.append(T)
        print(T.root, end=' ')
        T = T.lchild
      else:
        T = stack[-1]
        stack.pop()
        T = T.rchild

  # -----------中序遍历 ------------
  # 递归算法
  def mid_order_recursive(self, T):
    if T == None:
      return
    self.mid_order_recursive(T.lchild)
    print(T.root, end=' ')
    self.mid_order_recursive(T.rchild)

  # 非递归算法
  def mid_order_non_recursive(self, T):
    """借助栈实现中序遍历
    """
    if T == None:
      return
    stack = []
    while T or len(stack) > 0:
      if T:
        stack.append(T)
        T = T.lchild
      else:
        T = stack.pop()
        print(T.root, end=' ')
        T = T.rchild

  # -----------后序遍历 ------------
  # 递归算法
  def post_order_recursive(self, T):
    if T == None:
      return
    self.post_order_recursive(T.lchild)
    self.post_order_recursive(T.rchild)
    print(T.root, end=' ')

  # 非递归算法
  def post_order_non_recursive(self, T):
    """借助两个栈实现后序遍历
    """
    if T == None:
      return
    stack1 = []
    stack2 = []
    stack1.append(T)
    while stack1:
      node = stack1.pop()
      if node.lchild:
        stack1.append(node.lchild)
      if node.rchild:
        stack1.append(node.rchild)
      stack2.append(node)
    while stack2:
      print(stack2.pop().root, end=' ')
    return

  # -----------层次遍历 ------------
  def level_order(self, T):
    """借助队列(其实还是一个栈)实现层次遍历
    """
    if T == None:
      return
    stack = []
    stack.append(T)
    while stack:
      node = stack.pop(0) # 实现先进先出
      print(node.root, end=' ')
      if node.lchild:
        stack.append(node.lchild)
      if node.rchild:
        stack.append(node.rchild)

  # ----------- 前序遍历序列、中序遍历序列 —> 重构二叉树 ------------
  def tree_by_pre_mid(self, pre, mid):
    if len(pre) != len(mid) or len(pre) == 0 or len(mid) == 0:
      return
    T = NodeTree(pre[0])
    index = mid.index(pre[0])
    T.lchild = self.tree_by_pre_mid(pre[1:index + 1], mid[:index])
    T.rchild = self.tree_by_pre_mid(pre[index + 1:], mid[index + 1:])
    return T

  # ----------- 后序遍历序列、中序遍历序列 —> 重构二叉树 ------------
  def tree_by_post_mid(self, post, mid):
    if len(post) != len(mid) or len(post) == 0 or len(mid) == 0:
      return
    T = NodeTree(post[-1])
    index = mid.index(post[-1])
    T.lchild = self.tree_by_post_mid(post[:index], mid[:index])
    T.rchild = self.tree_by_post_mid(post[index:-1], mid[index + 1:])
    return T


if __name__ == '__main__':
  # ----------- 测试:前序、中序、后序、层次遍历 -----------
  # 创建二叉树
  nodeTree = NodeTree(1,
            lchild=NodeTree(2,
                    lchild=NodeTree(4,
                            rchild=NodeTree(7))),
            rchild=NodeTree(3,
                    lchild=NodeTree(5),
                    rchild=NodeTree(6)))
  T = BinTree()
  print('前序遍历递归\t')
  T.pre_order_recursive(nodeTree) # 前序遍历-递归
  print('\n')
  print('前序遍历非递归\t')
  T.pre_order_non_recursive(nodeTree) # 前序遍历-非递归
  print('\n')
  print('中序遍历递归\t')
  T.mid_order_recursive(nodeTree) # 中序遍历-递归
  print('\n')
  print('中序遍历非递归\t')
  T.mid_order_non_recursive(nodeTree) # 中序遍历-非递归
  print('\n')
  print('后序遍历递归\t')
  T.post_order_recursive(nodeTree) # 后序遍历-递归
  print('\n')
  print('后序遍历非递归\t')
  T.post_order_non_recursive(nodeTree) # 后序遍历-非递归
  print('\n')
  print('层次遍历\t')
  T.level_order(nodeTree) # 层次遍历
  print('\n')

  print('==========================================================================')

  # ----------- 测试:由遍历序列构造二叉树 -----------
  T = BinTree()
  pre = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
  mid = ['B', 'C', 'A', 'E', 'D', 'G', 'H', 'F', 'I']
  post = ['C', 'B', 'E', 'H', 'G', 'I', 'F', 'D', 'A']

  newT_pre_mid = T.tree_by_pre_mid(pre, mid) # 由前序序列、中序序列构造二叉树
  T.post_order_recursive(newT_pre_mid) # 获取后序序列
  print('\n')

  newT_post_mid = T.tree_by_post_mid(post, mid) # 由后序序列、中序序列构造二叉树
  T.pre_order_recursive(newT_post_mid) # 获取前序序列

运行结果

前序遍历递归 
1 2 4 7 3 5 6

前序遍历非递归 
1 2 4 7 3 5 6

中序遍历递归 
4 7 2 1 5 3 6

中序遍历非递归 
4 7 2 1 5 3 6

后序遍历递归 
7 4 2 5 6 3 1

后序遍历非递归 
7 4 2 5 6 3 1

层次遍历 
1 2 3 4 5 6 7

==========================================================================
C B E H G I F D A

A B C D E F G H I

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
从零学python系列之新版本导入httplib模块报ImportError解决方案
May 23 Python
Python多线程编程(四):使用Lock互斥锁
Apr 05 Python
详解Python的Django框架中的中间件
Jul 24 Python
利用python实现命令行有道词典的方法示例
Jan 31 Python
Python机器学习之决策树算法
Dec 22 Python
python定时检测无响应进程并重启的实例代码
Apr 22 Python
Pandas透视表(pivot_table)详解
Jul 22 Python
python django 原生sql 获取数据的例子
Aug 14 Python
pytorch实现focal loss的两种方式小结
Jan 02 Python
python orm 框架中sqlalchemy用法实例详解
Feb 02 Python
Python datetime 如何处理时区信息
Sep 02 Python
Python 操作SQLite数据库的示例
Oct 16 Python
python挖矿算力测试程序详解
Jul 03 #Python
如何用Python做一个微信机器人自动拉群
Jul 03 #Python
Python中的正则表达式与JSON数据交换格式
Jul 03 #Python
python实现共轭梯度法
Jul 03 #Python
python实现微信自动回复及批量添加好友功能
Jul 03 #Python
Python 中Django安装和使用教程详解
Jul 03 #Python
利用python求积分的实例
Jul 03 #Python
You might like
php实现简单的MVC框架实例
2015/09/23 PHP
php使用PDO下exec()函数查询执行后受影响行数的方法
2017/03/28 PHP
URL编码转换,escape() encodeURI() encodeURIComponent()
2006/12/27 Javascript
获取元素距离浏览器周边的位置的方法getBoundingClientRect
2013/04/17 Javascript
JS中getYear()和getFullYear()区别分析
2014/07/04 Javascript
jquery简单实现网页层的展开与收缩效果
2015/08/07 Javascript
基于jquery实现一个滚动的分步注册向导-附源码
2015/08/26 Javascript
完美实现八种js焦点轮播图(上篇)
2016/07/18 Javascript
jQuery Easyui加载表格出错时在表格中间显示自定义的提示内容
2016/12/08 Javascript
浅谈javascript alert和confirm的美化
2016/12/15 Javascript
AngularJS前端页面操作之用户修改密码功能示例
2017/03/27 Javascript
jQuery EasyUI window窗口使用实例代码
2017/12/25 jQuery
在vue项目中安装使用Mint-UI的方法
2017/12/27 Javascript
vue-baidu-map 进入页面自动定位的解决方案(推荐)
2018/04/28 Javascript
如何利用@angular/cli V6.0直接开发PWA应用详解
2018/05/06 Javascript
总结4个方面优化Vue项目
2019/02/11 Javascript
NodeJS实现同步的方法
2019/03/02 NodeJs
nodejs读取图片返回给浏览器显示
2019/07/25 NodeJs
编写v-for循环的技巧汇总
2020/12/01 Javascript
在Linux中通过Python脚本访问mdb数据库的方法
2015/05/06 Python
浅析Python 中整型对象存储的位置
2016/05/16 Python
Python中Collections模块的Counter容器类使用教程
2016/05/31 Python
Python 逐行分割大txt文件的方法
2017/10/10 Python
python保存数据到本地文件的方法
2018/06/23 Python
python检测IP地址变化并触发事件
2018/12/26 Python
python GUI实现小球满屏乱跑效果
2019/05/09 Python
使用python绘制cdf的多种实现方法
2020/02/25 Python
Selenium环境变量配置(火狐浏览器)及验证实现
2020/12/07 Python
windows系统Tensorflow2.x简单安装记录(图文)
2021/01/18 Python
10张动图学会python循环与递归问题
2021/02/06 Python
入团者的自我评价分享
2013/12/02 职场文书
多媒体专业自我鉴定
2014/02/28 职场文书
六年级小学生评语
2014/12/26 职场文书
春季运动会开幕词
2015/01/28 职场文书
2015年小学体育教师工作总结
2015/10/23 职场文书
python四个坐标点对图片区域最小外接矩形进行裁剪
2021/06/04 Python