国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python簡單定義與使用二叉樹示例

2020-02-23 00:06:42
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 瑞丽市| 柯坪县| 辽宁省| 濮阳市| 通州市| 工布江达县| 山东省| 阿荣旗| 琼海市| 临颍县| 安宁市| 和龙市| 合阳县| 墨玉县| 郁南县| 蓬莱市| 辽源市| 宁蒗| 凌云县| 灵武市| 黄石市| 西贡区| 新泰市| 武山县| 苏尼特右旗| 新和县| 武安市| 海林市| 蓝山县| 彭山县| 个旧市| 天峻县| 澄城县| 衢州市| 博乐市| 南漳县| 乌苏市| 通化市| 保亭| 乡城县| 图木舒克市|