python數(shù)據(jù)結(jié)構(gòu)之二叉樹的建立實(shí)例
先建立二叉樹節(jié)點(diǎn),有一個(gè)data數(shù)據(jù)域,left,right 兩個(gè)指針域
# -*- coding: utf - 8 - *-
class TreeNode(object):
def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data
class BTree(object):
def __init__(self, root=0):
self.root = root
手動(dòng)建立二叉樹
node1 = TreeNode(data=1)
node2 = TreeNode(node1, 0, 2)
node3 = TreeNode(data=3)
node4 = TreeNode(data=4)
node5 = TreeNode(node3, node4, 5)
node6 = TreeNode(node2, node5, 6)
node7 = TreeNode(node6, 0, 7)
node8 = TreeNode(data=8)
root = TreeNode(node7, node8, 'root')
bt = BTree(root)
然后會(huì)生成下面的二叉樹
# 生成的二叉樹
# ------------------------
# root
# 7 8
# 6
# 2 5
# 1 3 4
#
# -------------------------
除了 手動(dòng)一個(gè)個(gè)的制定 node 節(jié)點(diǎn),還可以創(chuàng)建一個(gè) create 方法,接受用戶輸入添加二叉樹節(jié)點(diǎn)。。。使用前續(xù)方式添加 ,代碼如下:
# -*- coding: utf - 8 - *-
class TreeNode(object):
def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data
class BTree(object):
def __init__(self, root=0):
self.root = root
def is_empty(self):
if self.root is 0:
return True
else:
return False
def create(self):
temp = input('enter a value:')
if temp is '#':
return 0
treenode = TreeNode(data=temp)
if self.root is 0:
self.root = treenode
treenode.left = self.create()
treenode.right = self.create()
使用create創(chuàng)建二叉樹
#運(yùn)行文件 在交互解釋器下面運(yùn)行
bt = BTree()
bt.create()
enter a value:9
enter a value:7
enter a value:6
enter a value:2
enter a value:1
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:5
enter a value:3
enter a value:'#'
enter a value:'#'
enter a value:4
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:8
enter a value:'#'
enter a value:'#'
通過 create 也可以得到同樣的效果
相關(guān)文章
python輸入一個(gè)水仙花數(shù)(三位數(shù)) 輸出百位十位個(gè)位實(shí)例
這篇文章主要介紹了python輸入一個(gè)水仙花數(shù)(三位數(shù)) 輸出百位十位個(gè)位實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
python實(shí)現(xiàn)基于兩張圖片生成圓角圖標(biāo)效果的方法
這篇文章主要介紹了python實(shí)現(xiàn)基于兩張圖片生成圓角圖標(biāo)效果的方法,實(shí)例分析了Python使用pil模塊進(jìn)行圖片處理的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
python實(shí)現(xiàn)將一維列表轉(zhuǎn)換為多維列表(numpy+reshape)
今天小編就為大家分享一篇python實(shí)現(xiàn)將一維列表轉(zhuǎn)換為多維列表(numpy+reshape),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Python基礎(chǔ)第三方模塊requests openpyxl
這篇文章主要為大家介紹了Python基礎(chǔ)第三方模塊requests openpyxl使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
Python 實(shí)現(xiàn)國(guó)產(chǎn)SM3加密算法的示例代碼
這篇文章主要介紹了Python 實(shí)現(xiàn)國(guó)產(chǎn)SM3加密算法的示例代碼,幫助大家更好的理解和學(xué)習(xí)密碼學(xué),感興趣的朋友可以了解下2020-09-09
Python實(shí)現(xiàn)Excel和CSV之間的相互轉(zhuǎn)換
通過使用Python編程語言,編寫腳本來自動(dòng)化Excel和CSV之間的轉(zhuǎn)換過程,可以批量處理大量文件,定期更新數(shù)據(jù),并集成轉(zhuǎn)換過程到自動(dòng)化工作流程中,本文將介紹如何使用Python 實(shí)現(xiàn)Excel和CSV之間的相互轉(zhuǎn)換,需要的朋友可以參考下2024-03-03
pandas讀取csv格式數(shù)據(jù)時(shí)header參數(shù)設(shè)置方法
本文主要介紹了pandas讀取csv格式數(shù)據(jù)時(shí)header參數(shù)設(shè)置方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

