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

相关文章
|
4天前
|
C++ Python Java
Java每日一练(20230501) 路径交叉、环形链表、被围绕的区域
Java每日一练(20230501) 路径交叉、环形链表、被围绕的区域
40 0
Java每日一练(20230501) 路径交叉、环形链表、被围绕的区域
|
4天前
|
机器学习/深度学习 存储 人工智能
python 字符串的三种定义方式
python 字符串的三种定义方式
12 1
|
4天前
|
Python
python 变量的定义和使用详解
python 变量的定义和使用详解
13 0
|
4天前
|
机器学习/深度学习 TensorFlow API
Python安装TensorFlow 2、tf.keras和深度学习模型的定义
Python安装TensorFlow 2、tf.keras和深度学习模型的定义
|
4天前
|
数据安全/隐私保护 Python
Python从入门到精通——2.2.1深入学习面向对象编程:类和对象的定义
Python从入门到精通——2.2.1深入学习面向对象编程:类和对象的定义
|
4天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
4天前
05-python之函数-函数的定义/函数的参数/函数返回值/函数说明文档/函数的嵌套使用/函数变量的作用域
05-python之函数-函数的定义/函数的参数/函数返回值/函数说明文档/函数的嵌套使用/函数变量的作用域
|
4天前
|
存储 Python
python字符串的定义讲解以及格式化案例
Python字符串是文本数据类型,可使用单引号或双引号定义。格式化字符串能插入变量值,常见方法有:1) `%` 运算符,如 `print(&quot;我的名字是 %s,我今年 %d 岁。&quot; % (&quot;张三&quot;, 25))`;2) `str.format()`,如 `print(&quot;我的名字是 {},我今年 {} 岁。&quot;.format(&quot;张三&quot;, 25))`;3) Python 3.6+ 的f-string,如 `print(f&quot;我的名字是 {name},我今年 {age} 岁。&quot;)`。
8 1
|
4天前
|
Python
Python模块的定义与应用
在Python编程中,模块是一个非常重要的概念。模块是包含Python定义和语句的文件,文件名通常以`.py`为后缀。模块将程序划分为不同的部分,使得代码更加清晰、易于维护,并且可以实现代码复用。本文将详细探讨Python模块的定义、创建、导入以及使用,帮助读者更好地理解和应用模块。
|
4天前
|
Python
Python类定义:从小白到专家的旅程
Python类定义:从小白到专家的旅程
8 0