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 相关文章推荐
在Gnumeric下使用Python脚本操作表格的教程
Apr 14 Python
两个使用Python脚本操作文件的小示例分享
Aug 27 Python
Python实现获取域名所用服务器的真实IP
Oct 25 Python
Python使用回溯法子集树模板解决迷宫问题示例
Sep 01 Python
python和ruby,我选谁?
Sep 13 Python
手把手教你用python抢票回家过年(代码简单)
Jan 21 Python
特征脸(Eigenface)理论基础之PCA主成分分析法
Mar 13 Python
使用matplotlib画散点图的方法
May 25 Python
Python Django 前后端分离 API的方法
Aug 28 Python
Python常驻任务实现接收外界参数代码解析
Jul 21 Python
python中类与对象之间的关系详解
Dec 16 Python
Python3接口性能测试实例代码
Jun 20 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的正则处理函数总结分析
2008/06/20 PHP
php中substr()函数参数说明及用法实例
2014/11/15 PHP
CodeIgniter常用知识点小结
2016/05/26 PHP
PHP学习笔记之session
2018/05/06 PHP
php 中phar包的使用教程详解
2018/10/26 PHP
jquery实现心算练习代码
2010/12/06 Javascript
JS获取浏览器版本及名称实现函数
2013/04/02 Javascript
将nodejs打包工具整合到鼠标右键的方法
2013/05/11 NodeJs
单击浏览器右上角的X关闭窗口弹出提示的小例子
2013/06/12 Javascript
JavaScript中获取高度和宽度函数总结
2014/10/08 Javascript
nodejs批量修改文件编码格式
2015/01/22 NodeJs
jquery性能优化高级技巧
2015/08/24 Javascript
Bootstrap轮播插件中图片变形的终极解决方案 使用jqthumb.js
2016/07/10 Javascript
js 动态添加元素(div、li、img等)及设置属性的方法
2016/07/19 Javascript
如何提高数据访问速度
2016/12/26 Javascript
浅谈React中组件间抽象
2018/01/27 Javascript
vue动态绑定组件子父组件多表单验证功能的实现代码
2018/05/14 Javascript
微信小程序实现跑马灯效果完整代码(附效果图)
2018/05/30 Javascript
JavaScript实现答题评分功能页面
2020/06/24 Javascript
js实现简单抽奖功能
2020/11/24 Javascript
[48:48]2014 DOTA2国际邀请赛中国区预选赛 SPD-GAMING VS Dream TIME
2014/05/21 DOTA
浅析python 中大括号中括号小括号的区分
2019/07/29 Python
使用Python和百度语音识别生成视频字幕的实现
2020/04/09 Python
Tensorflow中的图(tf.Graph)和会话(tf.Session)的实现
2020/04/22 Python
Django 解决由save方法引发的错误
2020/05/21 Python
如何用python 操作zookeeper
2020/12/28 Python
美体小铺加拿大官方网站:The Body Shop加拿大
2016/10/30 全球购物
单位工程竣工验收方案
2014/03/16 职场文书
法人代表身份证明书及授权委托书
2014/09/16 职场文书
2014党的群众路线教育实践活动总结报告
2014/10/31 职场文书
2014城乡环境综合治理工作总结
2014/12/19 职场文书
公司保洁员岗位职责
2015/02/13 职场文书
无故旷工检讨书
2015/08/15 职场文书
村官2015年度工作总结
2015/10/14 职场文书
golang elasticsearch Client的使用详解
2021/05/05 Golang
Python re.sub 反向引用的实现
2021/07/07 Python