Python 二叉樹資料結構

2022-08-23 12:06:13 字數 2215 閱讀 5110

二叉樹是每個結點最多有兩個子樹的樹結構。通常子樹被稱作「左子樹」(left subtree)和「右子樹」(right subtree)。

將二叉樹的節點定義為乙個物件,節點之間通過類似鍊錶的鏈結方式來連線。

二叉樹的遍歷方式:

前序遍歷:eacbdgf

中序遍歷:abcdegf

後序遍歷:bdcafge

層次遍歷:eagcfbd

#

_*_ coding=utf-8 _*_

"""實現乙個二叉樹結果,並進行遍歷

e/ \

a g

\ \

c f

/ \b d

"""from collections import

deque

class

binarytree(object):

def__init__

(self, data):

self.data =data

self.child_l =none

self.child_r =none#建立

a = binarytree("a"

)b = binarytree("b"

)c = binarytree("c"

)d = binarytree("d"

)e = binarytree("e"

)f = binarytree("f"

)g = binarytree("g"

)#構造節點關係

e.child_l =a

e.child_r =g

a.child_r =c

c.child_l =b

c.child_r =d

g.child_r =f

#設定根

root =e

defpre_order(tree):

"""前序遍歷:root -> child_l -> child_r

:param tree: the root of tree

:return:

"""if

tree:

print(tree.data, end=','

)

#print("")

pre_order(tree.child_l)

pre_order(tree.child_r)

defin_order(tree):

"""中序遍歷:child_l -> root -> child_r

:param tree:

:return:

"""if

tree:

in_order(tree.child_l)

print(tree.data, end=','

) in_order(tree.child_r)

defpost_order(tree):

"""後序遍歷:child_l -> child_r -> root

:param tree:

:return:

"""if

tree:

post_order(tree.child_l)

post_order(tree.child_r)

print(tree.data, end=','

)def

level_order(tree):

"""層次遍歷:e -> ag -> cf -> bd

使用佇列實現

:param tree:

:return:

"""queue =deque()

#先把根新增到佇列

while len(queue): #

佇列不為空

node =queue.popleft()

print(node.data, end=','

)

ifnode.child_l:

ifnode.child_r:

pre_order(root)

print(''

)in_order(root)

print(''

)post_order(root)

print(''

)level_order(root)

重建二叉樹python 資料結構 重建二叉樹

說明 給定輸入一棵二叉樹的前序遍歷和中序遍歷陣列。利用此重新建立二叉樹。注意輸入不包含相同的鍵值,否則情況複雜得多。思路 由定義,前序遍歷的第乙個記錄總是根節點,而這個鍵值在中序遍歷時,將中序遍歷的陣列分成兩部分,分別對應這個根節點的左右兩子樹。同時,前序遍歷陣列跟在節點後的陣列也分成兩部分,其中前...

資料結構 二叉樹 反轉二叉樹

include using namespace std define maxsize 1000 struct binary tree node class queue queue queue void queue push binary tree node btn binary tree node ...

《資料結構》 二叉樹

二叉樹 是 n個結點的有限集,它或為空集,或由乙個根結點及兩棵互不相交的 分別稱為該根的左子樹和右子樹的二叉樹組成。二叉樹不是樹的特殊情況,這是兩種不同的資料結構 它與無序樹和度為 2的有序樹不同。二叉樹的性質 1 二叉樹第 i層上的結點數最多為 2 i 1 2 深度為 k的二叉樹至多有 2 k 1...