Python简单定义与使用二叉树示例

yipeiwu_com5年前Python基础

本文实例讲述了Python简单定义与使用二叉树的方法。分享给大家供大家参考,具体如下:

class BinaryTree:
  def __init__(self,rootObj):
    self.root = rootObj
    self.leftChild = None
    self.rightChild = None
  def insertLeft(self,newNode):
    if self.leftChild == None:
      self.leftChild = BinaryTree(newNode)
    else:
      print('The leftChild is not None.You can not insert')
  def insertRight(self,newNode):
    if self.rightChild == None:
      self.rightChild = BinaryTree(newNode)
    else:
      print('The rightChild is not None.You can not insert')

构建了一个简单的二叉树类,它的初始化函数,将传入的rootObj赋值给self.root,作为根节点,leftChild和rightChild都默认为None。

函数insertLeft为向二叉树的左子树赋值,若leftChild为空,则先构造一个BinaryTree(newNode),即实例化一个新的二叉树,然后将这棵二叉树赋值给原来的二叉树的leftChild。此处递归调用了BinaryTree这个类。

若不为空 则输出:The rightChild is not None.You can not insert

执行下述语句

r = BinaryTree('a')
print('root:',r.root,';','leftChild:',r.leftChild,';','rightChild:',r.rightChild)

输出

root: a ; leftChild: None ; rightChild: None

即我们构造了一颗二叉树,根节点为a,左右子树均为None

然后执行下述语句

r.insertLeft('b')
print('root:',r.root,';','leftChild:',r.leftChild,';','rightChild:',r.rightChild)
print('root:',r.root,';','leftChild.root:',r.leftChild.root,';','rightChild:',r.rightChild)

输出

root: a ; leftChild: <__main__.BinaryTree object at 0x000002431E4A0DA0> ; rightChild: None
root: a ; leftChild.root: b ; rightChild: None

我们向r插入了一个左节点,查看输出的第一句话,可以看到左节点其实也是一个BinaryTree,这是因为插入时,递归生成的。

第二句输出,可以查看左节点的值

最后执行

r.insertLeft('c')

输出:

The leftChild is not None.You can not insert

可以看到,我们无法再向左节点插入了,因为该节点已经有值了

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

详解python之协程gevent模块

Gevent官网文档地址:http://www.gevent.org/contents.html 进程、线程、协程区分 我们通常所说的协程Coroutine其实是corporate ro...

小米5s微信跳一跳小程序python源码

本文实例为大家分享了微信跳一跳小程序python源码,供大家参考,具体内容如下 微信跳一跳小程序小米5s源码python,搭建环境后亲测可用。 # coding: utf-8 imp...

用Python调用win命令行提高工作效率的实例

用Python调用win命令行提高工作效率的实例

作为程序猿,每天一上班打开电脑要做的时候就是打开各种工作所需的工具,如QQ,SQL Server,浏览器,编辑器等,每天都要一个个点,重复性的工作做多了也觉得烦(关键是影响了我上班倒水的...

python中实现php的var_dump函数功能

python中实现php的var_dump函数功能

最近在做python的web开发(原谅我的多变,好东西总想都学着。。。node.js也是),不过过程中总遇到些问题,不管是web.py还是django,开发起来确实没用php方便,毕竟存...

Tensorflow 同时载入多个模型的实例讲解

有时我们希望在一个python的文件空间同时载入多个模型,例如 我们建立了10个CNN模型,然后我们又写了一个预测类Predict,这个类会从已经保存好的模型restore恢复相应的图结...