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函数的笔记整理
Apr 07 Python
进一步了解Python中的XML 工具
Apr 13 Python
详细讲解用Python发送SMTP邮件的教程
Apr 29 Python
Python实现HTTP协议下的文件下载方法总结
Apr 20 Python
微信跳一跳游戏python脚本
Apr 01 Python
关于Python正则表达式 findall函数问题详解
Mar 22 Python
python网络爬虫学习笔记(1)
Apr 09 Python
python实现多层感知器
Jan 18 Python
Python提取特定时间段内数据的方法实例
Apr 01 Python
windows下安装Python虚拟环境virtualenvwrapper-win
Jun 14 Python
解决pycharm启动后总是不停的updating indices...indexing的问题
Nov 27 Python
解决python中import文件夹下面py文件报错问题
Jun 01 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手机号码归属地查询代码(API接口/mysql)
2012/09/04 PHP
PHP输出两个数字中间有多少个回文数的方法
2015/03/23 PHP
Smarty3配置及入门语法
2017/02/22 PHP
php类自动装载、链式操作、魔术方法实现代码
2017/07/23 PHP
Thinkphp5行为使用方法汇总
2017/12/21 PHP
PHP实现数组转JSon和JSon转数组的方法示例
2018/06/14 PHP
Prototype 学习 工具函数学习($w,$F方法)
2009/07/12 Javascript
Javascript 继承机制的实现
2009/08/12 Javascript
JQuery 插件制作实践 xMarquee插件V1.0
2010/04/02 Javascript
niceTitle 基于jquery的超链接提示插件
2010/05/31 Javascript
Window.Open如何在同一个标签页打开
2014/06/20 Javascript
基于JS实现textarea中获取动态剩余字数的方法
2016/05/25 Javascript
AngularJS动态绑定HTML的方法分析
2016/11/07 Javascript
Bootstrap Search Suggest使用例子
2016/12/21 Javascript
mescroll.js上拉加载下拉刷新组件使用详解
2017/11/13 Javascript
JavaScript实现指定数量的并发限制的示例代码
2020/03/10 Javascript
[03:56]显微镜下的DOTA2第十一期——鬼畜的死亡先知播音员
2014/06/23 DOTA
[00:36]TI7不朽珍藏III——斯温不朽展示
2017/07/15 DOTA
python中map、any、all函数用法分析
2015/04/21 Python
python字典的常用操作方法小结
2016/05/16 Python
利用Anaconda完美解决Python 2与python 3的共存问题
2017/05/25 Python
python利用OpenCV2实现人脸检测
2020/04/16 Python
Python logging模块用法示例
2018/08/28 Python
对Python w和w+权限的区别详解
2019/01/23 Python
Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题
2019/07/15 Python
python中绕过反爬虫的方法总结
2020/11/25 Python
澳大利亚最受欢迎的美发和美容在线商店:Catwalk
2018/12/12 全球购物
UNIX文件类型
2013/08/29 面试题
门卫人员岗位职责
2013/12/24 职场文书
优秀安全员事迹材料
2014/05/11 职场文书
白血病捐款倡议书
2014/05/14 职场文书
党的群众路线对照检查材料范文
2014/09/24 职场文书
学校政风行风评议工作总结
2014/10/21 职场文书
小学教师教学随笔
2015/08/14 职场文书
如何写好活动总结
2019/06/21 职场文书
十个Python自动化常用操作,即拿即用
2021/05/10 Python