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
可以看到,我们无法再向左节点插入了,因为该节点已经有值了

相关文章
|
1天前
|
存储 Python
Python字典的定义与操作详解
Python字典的定义与操作详解
4 1
|
1天前
|
索引 Python
Python集合的定义与操作详解
Python集合的定义与操作详解
2 1
|
1天前
|
索引 Python
Python字符串的定义与操作详解
Python字符串的定义与操作详解
5 1
|
1天前
|
存储 索引 Python
Python元组的定义与操作详解
Python元组的定义与操作详解
4 1
|
13天前
|
Python
2024年最新【Python】变量 的定义和使用,阿里巴巴蚂蚁金服面试流程
2024年最新【Python】变量 的定义和使用,阿里巴巴蚂蚁金服面试流程
2024年最新【Python】变量 的定义和使用,阿里巴巴蚂蚁金服面试流程
|
18天前
|
机器学习/深度学习 存储 人工智能
python 字符串的三种定义方式
python 字符串的三种定义方式
14 1
|
18天前
|
Python
python 变量的定义和使用详解
python 变量的定义和使用详解
16 0
|
18天前
|
机器学习/深度学习 TensorFlow API
Python安装TensorFlow 2、tf.keras和深度学习模型的定义
Python安装TensorFlow 2、tf.keras和深度学习模型的定义
|
18天前
|
数据安全/隐私保护 Python
Python从入门到精通——2.2.1深入学习面向对象编程:类和对象的定义
Python从入门到精通——2.2.1深入学习面向对象编程:类和对象的定义
|
18天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数