Python簡單定義與使用二叉樹示例
本文實例講述了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)建了一個簡單的二叉樹類,它的初始化函數(shù),將傳入的rootObj賦值給self.root,作為根節(jié)點(diǎn),leftChild和rightChild都默認(rèn)為None。
函數(shù)insertLeft為向二叉樹的左子樹賦值,若leftChild為空,則先構(gòu)造一個BinaryTree(newNode),即實例化一個新的二叉樹,然后將這棵二叉樹賦值給原來的二叉樹的leftChild。此處遞歸調(diào)用了BinaryTree這個類。
若不為空 則輸出: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插入了一個左節(jié)點(diǎn),查看輸出的第一句話,可以看到左節(jié)點(diǎn)其實也是一個BinaryTree,這是因為插入時,遞歸生成的。
第二句輸出,可以查看左節(jié)點(diǎn)的值
最后執(zhí)行
r.insertLeft('c')
輸出:
The leftChild is not None.You can not insert
可以看到,我們無法再向左節(jié)點(diǎ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è)計有所幫助。
- python數(shù)據(jù)結(jié)構(gòu)之二叉樹的建立實例
- python數(shù)據(jù)結(jié)構(gòu)之二叉樹的遍歷實例
- Python中的二叉樹查找算法模塊使用指南
- Python利用前序和中序遍歷結(jié)果重建二叉樹的方法
- python數(shù)據(jù)結(jié)構(gòu)樹和二叉樹簡介
- python二叉樹遍歷的實現(xiàn)方法
- python二叉樹的實現(xiàn)實例
- python數(shù)據(jù)結(jié)構(gòu)之二叉樹的統(tǒng)計與轉(zhuǎn)換實例
- Python實現(xiàn)重建二叉樹的三種方法詳解
- Python二叉樹初識(新手也秒懂!)
相關(guān)文章
linux系統(tǒng)使用python監(jiān)測網(wǎng)絡(luò)接口獲取網(wǎng)絡(luò)的輸入輸出
這篇文章主要介紹了linux系統(tǒng)使用python監(jiān)測網(wǎng)絡(luò)接口獲取網(wǎng)絡(luò)的輸入輸出信息,大家參考使用吧2014-01-01Python中shapefile轉(zhuǎn)換geojson的示例
今天小編就為大家分享一篇關(guān)于Python中shapefile轉(zhuǎn)換geojson的示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01Python入門教程(十七)Python的While循環(huán)
這篇文章主要介紹了Python入門教程(十七)Python的While循環(huán),Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下2023-04-04python狀態(tài)機(jī)transitions庫詳解
在用python做一個比較復(fù)雜的小項目,需要根據(jù)不同的輸入,控制攝像頭采集執(zhí)行不同的任務(wù).雖然用流程方式實現(xiàn)了,但閱讀起來費(fèi)勁,還容易出錯.所以就用了狀態(tài)機(jī),需要的朋友可以參考下2021-06-06