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流程控制 if else实现解析

Python流程控制 if else实现解析

一、流程控制 假如把程序比做走路,那我们到现在为止,一直走的都是直路,还没遇到过分岔口。当遇到分岔口时,你得判断哪条岔路是你要走的路,如果我们想让程序也能处理这样的判断,该怎么办?很简...

利用pandas读取中文数据集的方法

利用pandas读取中文数据集的方法

直接利用numpy读取非数字型的数据集时需要先进行转换,而且python3在处理中文数据方面确实比较蛋疼。最近在学习周志华老师的那本西瓜书,需要没事和一堆西瓜反复较劲,之前进行联系的时候...

python脚本后台执行方式

在Linux中,可以使用nohup将脚本放置后台运行,如下: nohup python myscript.py params1 > nohup.out 2>&1 &...

python3利用Dlib19.7实现人脸68个特征点标定

python3利用Dlib19.7实现人脸68个特征点标定

0.引言 利用Dlib官方训练好的模型“shape_predictor_68_face_landmarks.dat”进行68点标定,利用OpenCv进行图像化处理,在人脸上画出68个点,...

python面向对象入门教程之从代码复用开始(一)

前言 本文从代码复用的角度一步一步演示如何从python普通代码进化到面向对象,并通过代码去解释一些面向对象的理论。所以,本文前面的内容都是非面向对象的语法实现方式,只有在最结尾才给出了...