教你如何使用Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)及三種遍歷
一:代碼實(shí)現(xiàn)
class TreeNode:
"""節(jié)點(diǎn)類"""
def __init__(self, mid, left=None, right=None):
self.mid = mid
self.left = left
self.right = right
# 樹(shù)類
class Tree:
"""樹(shù)類"""
def __init__(self, root=None):
self.root = root
def add(self, item):
# 將要添加的數(shù)據(jù)封裝成一個(gè)node結(jié)點(diǎn)
node = TreeNode(item)
if not self.root:
self.root = node
return
queue = [self.root]
while queue:
cur = queue.pop(0)
if not cur.left:
cur.left = node
return
else:
queue.append(cur.left)
if not cur.right:
cur.right = node
return
else:
queue.append(cur.right)
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
二:遍歷
在上述樹(shù)類代碼基礎(chǔ)上加遍歷函數(shù),基于遞歸實(shí)現(xiàn)。

先序遍歷:
先序遍歷結(jié)果是:0 -> 1 -> 3 -> 4 -> 2 -> 5 -> 6
# 先序遍歷
def preorder(self, root, result=[]):
if not root:
return
result.append(root.mid)
self.preorder(root.left, result)
self.preorder(root.right, result)
return result
print("先序遍歷")
print(tree.preorder(tree.root))
"""
先序遍歷
[0, 1, 3, 4, 2, 5, 6]
"""
中序遍歷:
中序遍歷結(jié)果是:3 -> 1 -> 4 -> 0 -> 5 -> 2 -> 6
# 中序遍歷
def inorder(self, root, result=[]):
if not root:
return result
self.inorder(root.left, result)
result.append(root.mid)
self.inorder(root.right, result)
return result
print("中序遍歷")
print(tree.inorder(tree.root))
"""
中序遍歷
3, 1, 4, 0, 5, 2, 6]
"""
后續(xù)遍歷
后序遍歷結(jié)果是:3 -> 4 -> 1 -> 5 -> 6 -> 2 -> 0
# 后序遍歷
def postorder(self, root, result=[]):
if not root:
return result
self.postorder(root.left, result)
self.postorder(root.right, result)
result.append(root.mid)
return result
print("后序遍歷")
print(tree.postorder(tree.root))
"""
后序遍歷
[3, 4, 1, 5, 6, 2, 0]
"""
到此這篇關(guān)于教你如何使用Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)及三種遍歷的文章就介紹到這了,更多相關(guān)Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)及三種遍歷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python flask框架實(shí)現(xiàn)瀏覽器點(diǎn)擊自定義跳轉(zhuǎn)頁(yè)面
這篇文章主要介紹了Python flask框架實(shí)現(xiàn)瀏覽器點(diǎn)擊自定義跳轉(zhuǎn)頁(yè)面,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Python針對(duì)給定字符串求解所有子序列是否為回文序列的方法
這篇文章主要介紹了Python針對(duì)給定字符串求解所有子序列是否為回文序列的方法,涉及Python針對(duì)字符串的遍歷、判斷、運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
Python PyQt5標(biāo)準(zhǔn)對(duì)話框用法示例
這篇文章主要介紹了Python PyQt5標(biāo)準(zhǔn)對(duì)話框用法,結(jié)合實(shí)例形式分析了PyQt5常用的標(biāo)準(zhǔn)對(duì)話框及相關(guān)使用技巧,需要的朋友可以參考下2017-08-08
10個(gè)Python辦公自動(dòng)化案例總結(jié)
Python作為一種簡(jiǎn)單而強(qiáng)大的編程語(yǔ)言,不僅在數(shù)據(jù)科學(xué)和軟件開(kāi)發(fā)領(lǐng)域廣受歡迎,還在辦公自動(dòng)化方面發(fā)揮了巨大作用,通過(guò)Python,我們可以編寫腳本來(lái)自動(dòng)執(zhí)行各種重復(fù)性任務(wù),從而提高工作效率并減少錯(cuò)誤,在本文中,我們總結(jié)了10個(gè)Python辦公自動(dòng)化案例2024-09-09
Pycharm 創(chuàng)建 Django admin 用戶名和密碼的實(shí)例
今天小編就為大家分享一篇Pycharm 創(chuàng)建 Django admin 用戶名和密碼的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05

