寫在最前面:
帶你從最簡(jiǎn)單的二叉樹構(gòu)造開始,深入理解二叉樹的數(shù)據(jù)結(jié)構(gòu),ps:不會(huì)數(shù)據(jù)結(jié)構(gòu)的程序猿只能是三流的
首先,我們構(gòu)造一個(gè)二叉樹
這是最標(biāo)準(zhǔn),也是最簡(jiǎn)單的二叉樹構(gòu)造方法
'''
樹的構(gòu)建:
3
9 20
15 7
'''
class Tree():
'樹的實(shí)現(xiàn)'
def __init__(self,data,left = 0,right = 0):
self.left = left
self.right = right
self.data = data
def __str__(self):
return str(self.data)
# test tree
tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
這里我們需要定義二叉樹的根,左右節(jié)點(diǎn),然后構(gòu)造節(jié)點(diǎn)之間的關(guān)系
打印二叉樹函數(shù)
def function(root):
A = []
result = []
if not root:
return result
A.append(root)
while A:
current_root = A.pop(0)
result.append(current_root.data)
if current_root.left:
A.append(current_root.left)
if current_root.right:
A.append(current_root.right)
print(result)
return result
調(diào)用函數(shù)以及放入構(gòu)造好的二叉樹
function(base)
輸出如下:
[3, 9, 20, 15, 7]
Process finished with exit code 0
最近事情實(shí)在是太多,真的是每天人都很累,還是堅(jiān)持每天更新一點(diǎn),已經(jīng)快要強(qiáng)迫癥了。
以上這篇基于python二叉樹的構(gòu)造和打印例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

