最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2018年05月11日 10:55:32   作者:Tao-Tao-Tao  
這篇文章主要介紹了Python簡單定義與使用二叉樹,結(jié)合實(shí)例形式分析了Python定義二叉樹及節(jié)點(diǎn)插入相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了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')

構(gòu)建了一個(gè)簡單的二叉樹類,它的初始化函數(shù),將傳入的rootObj賦值給self.root,作為根節(jié)點(diǎn),leftChild和rightChild都默認(rèn)為None。

函數(shù)insertLeft為向二叉樹的左子樹賦值,若leftChild為空,則先構(gòu)造一個(gè)BinaryTree(newNode),即實(shí)例化一個(gè)新的二叉樹,然后將這棵二叉樹賦值給原來的二叉樹的leftChild。此處遞歸調(diào)用了BinaryTree這個(gè)類。

若不為空 則輸出:The rightChild is not None.You can not insert

執(zhí)行下述語句

r = BinaryTree('a')
print('root:',r.root,';','leftChild:',r.leftChild,';','rightChild:',r.rightChild)

輸出

root: a ; leftChild: None ; rightChild: None

即我們構(gòu)造了一顆二叉樹,根節(jié)點(diǎn)為a,左右子樹均為None

然后執(zhí)行下述語句

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插入了一個(gè)左節(jié)點(diǎn),查看輸出的第一句話,可以看到左節(jié)點(diǎn)其實(shí)也是一個(gè)BinaryTree,這是因?yàn)椴迦霑r(shí),遞歸生成的。

第二句輸出,可以查看左節(jié)點(diǎn)的值

最后執(zhí)行

r.insertLeft('c')

輸出:

The leftChild is not None.You can not insert

可以看到,我們無法再向左節(jié)點(diǎn)插入了,因?yàn)樵摴?jié)點(diǎn)已經(jīng)有值了

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

昔阳县| 邯郸县| 峨山| 修文县| 子长县| 蒙自县| 文成县| 涪陵区| 常州市| 宁武县| 旅游| 清河县| 深圳市| 汶川县| 纳雍县| 平泉县| 通辽市| 高阳县| 拉孜县| 西畴县| 隆子县| 邯郸市| 岳西县| 巩义市| 威远县| 通江县| 宣化县| 精河县| 太谷县| 海晏县| 东丰县| 柯坪县| 蒙自县| 资溪县| 五台县| 开江县| 通城县| 应用必备| 哈密市| 清原| 清水县|