本文实例讲述了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程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?
更新日志
- 许巍《许巍精选专辑》[FLAC/分轨][1.9GB]
- 群星.2024-繁花电视剧原声带3CD【环球】【WAV+CUE】
- 江希文.1994-伝说少女(饿狼伝说动画原声大碟)【嘉音】【WAV+CUE】
- 洪荣宏.2010-上爱的人【华特】【WAV+CUE】
- 《大牌国语情歌 经典再现 深情对唱 2CD》[WAV/分轨][900MB]
- 《陈百强粉红色的一生精选 3CD》[FLAC/分轨][1.2GB]
- 《丁当 20首重量级歌曲 Fu Good 下一站天后 2CD》[WAV/分轨][650MB]
- 歌莉雅.2012-My.Voice.Story【环星】【FLAC分轨】
- 群星.1993-一曲成名·青春无悔【飞碟】【WAV+CUE】
- 刘德华.2000-爱无知(金装版)【NEWMELODY】【WAV+CUE】
- 许巍《时光漫步》1CD[FLAC/分轨][804.3MB]
- 群星《2024第一季度百度歌曲排行抖音榜top100》1CD[FLAC/分轨][2.3GB]
- 张柏芝《全新经验》[FLAC/分轨][450MB]
- 唐朝.2008-浪漫骑士【音乐家】【WAV+CUE】
- 张芸京.2016-失败的高歌【泡耳音乐】【WAV+CUE】