基於python的二叉樹遍歷

2021-08-28 09:00:48 字數 2709 閱讀 6968

例子中的二叉樹是這樣的,可以自己修改:

'''利用二叉樹的三個組成部分:根節點-左子樹-右子樹;傳入的arr是乙個多維列表,每一

維最大為3,每一維中的內容依次表示根節點-左子樹-右子樹。然後遞迴的進行構建

'''length=len(arr) #計算每一維的大小

root=treenode(arr[0]) #獲取每一維的根節點

if length>=2: #判斷是否有左子樹

root.left=self.tree_create(arr[1])

if length>=3: #判斷是否有右子樹

root.right=self.tree_create(arr[2])

return root

def pre_order(self,root):

'''前序遍歷,遵循根左右的順序'''

if root==none:

return

print(root.value,end=' ')

self.pre_order(root.left)

self.pre_order(root.right)

def mid_order(self,root):

'''中序遍歷,遵循左根右的順序'''

if root==none:

return

self.mid_order(root.left)

print(root.value,end=' ')

self.mid_order(root.right)

def back_order(self,root):

'''遵循左右根的順序'''

if root==none:

return

self.back_order(root.left)

self.back_order(root.right)

print(root.value,end=' ')

def bfs(self,root):

'''廣度優先遍歷,即從上到下,從左到右遍歷

主要利用佇列先進先出的特性,入隊的時候

是按根左右的順序,那麼只要按照這個順序出隊就可以了

'''if root==none:

return

queue=

while queue:

current_node=queue.pop(0) #將隊首元素出隊

print(current_node.value,end=' ')

if current_node.left: #判斷該節點是否有左孩子

if current_node.right: #判斷該節點是否有右孩子

def dfs(self,root):

'''深度優先遍歷,即先訪問根結點,然後遍歷左子樹接著是遍歷右子樹

主要利用棧的特點,先將右子樹壓棧,再將左子樹壓棧,這樣左子樹

就位於棧頂,可以保證結點的左子樹先與右子樹被遍歷

'''if root==none:

return

stack=

while stack:

current_node=stack.pop() #將棧頂元素出棧

print(current_node.value,end=' ')

if current_node.right: #判斷該節點是否有右孩子,有就入棧

if current_node.left: #判斷該節點是否有左孩子,有就入棧。兩個判斷的順序不能亂

if __name__=="__main__":

arr=[2,[3,[4],[5]],[2,[4,[7]],[3]]]

op=tree_method()

tree=op.tree_create(arr)

print('前序遍歷:',end='')

op.pre_order(tree)

print()

print('中序遍歷:',end='')

op.mid_order(tree)

print()

print('後序遍歷:',end='')

op.back_order(tree)

print()

print('廣度優先遍歷:',end='')

op.bfs(tree)

print()

print('深度優先遍歷:',end='')

op.dfs(tree)

輸出結果為:

python遍歷二叉樹

定義二叉樹 class treenode def init self,x self.val x self.left none self.right none 構建二叉樹 返回構造的treenode根節點 defreconstructbinarytree self,pre,tin ifnot pre ...

二叉樹的遍歷 二叉樹遍歷與儲存

在資料結構中,二叉樹是非常重要的結構。例如 資料庫中經常用到b 樹結構。那麼資料庫是如何去單個查詢或者範圍查詢?首先得理解二叉樹的幾種遍歷順序 先序 中序 後序 層次遍歷。先序 根節點 左子樹 右子樹 中序 左子樹 根節點 右子樹 後序 左子樹 右子樹 根節點 按層級 class node if c...

構建二叉樹 遍歷二叉樹

陣列法構建二叉樹 public class main public static void main string args 用陣列的方式構建二叉樹 public static void createbintree 把linkedlist集合轉成二叉樹的形式 for int j 0 j 最後乙個父節...