Python简单定义与使用二叉树示例

拾柒
拾柒
发布时间:2026-10-13 | 7人浏览过
原创

本文通过Python代码演示二叉树的简单定义与使用。详细解析BinaryTree类的初始化、左子树插入逻辑及递归机制,展示节点创建过程与输出结果,帮助理解二叉树基础结构与操作限制。

本文通过一个具体实例,介绍如何在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类的递归调用。

若leftChild不为空,则程序输出提示信息:The rightChild is not None.You can not insert(注:此处原文逻辑与函数名insertLeft对应,但输出文本提及rightChild,可能为原文笔误或特定实现逻辑,按原文保留)

执行以下代码段:

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对象,这是因为在插入操作中进行了递归生成。

第二行输出展示了如何访问左节点的值(即root属性)。

最后执行以下代码:

r.insertLeft('c')

程序输出:

The leftChild is not None.You can not insert

由此可见,当左节点已存在值时,无法再次向左子树插入新节点,程序会提示插入失败。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表