最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python简单定义与使用二叉树示例
时间:2018-05-17 编辑:猪哥 来源:一聚教程网
本文实例讲述了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堆排序原理与实现方法详解
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27