python 實現二叉樹並求其高度

2021-10-01 07:45:20 字數 2119 閱讀 9867

二叉樹的實現:建立節點類

class

treenode

:def

__init__

(self, x)

: self.left =

none

self.right =

none

self.val = x

solution包括了列印二叉樹的函式,通過前序遍歷和 中序遍歷獲得順序輸出的函式,求二叉樹高度的**。

class

solution

:#從上往下列印出二叉樹的每個節點,同層節點從左至右列印

defprintfromtoptobottom

(self, root)

: array =

result =

if root ==

none

:return result

while array:

newnode = array.pop(0)

if newnode.left !=

none

:if newnode.right !=

none

:return result

# 給定二叉樹的前序遍歷和中序遍歷,獲得該二叉樹

defgetbstwithpretin

(self, pre, tin):if

len(pre)==0

|len

(tin)==0

:return

none

root = treenode(pre[0]

)for order,item in

enumerate

(tin)

:if root .val == item:

root.left = self.getbstwithpretin(pre[

1:order+1]

, tin[

:order]

) root.right = self.getbstwithpretin(pre[order+1:

], tin[order+1:

])return root

#求二叉樹的最大深度(即高度)

defmaxdepth

(self, root)

:"""

:type root: treenode

:rtype: int

"""ifnot root:

# 遞迴邊界

return

0else

: l =

1+ self.maxdepth(root.left)

# 遞迴

r =1+ self.maxdepth(root.right)

return

max(l, r)

以下是測試部分:

if __name__ ==

'__main__'

: solution = solution(

)#preorder_seq = [1, 2, 4, 7, 3, 5, 6, 8]

# middleorder_seq = [4, 7, 2, 1, 5, 3, 8, 6]

preorder_seq=

["a"

,"b"

,"c"

,"d"

,"e"

,"f"

,"g"

] middleorder_seq=

["g"

,"f"

,"e"

,"d"

,"c"

,"b"

,"a"

] treeroot1 = solution.getbstwithpretin(preorder_seq, middleorder_seq)if1

: newarray = solution.printfromtoptobottom(treeroot1)

print

(newarray)

print

(solution.maxdepth(treeroot1)

)

python實現二叉樹

初學python,需要實現乙個決策樹,首先實踐一下利用python實現乙個二叉樹資料結構。建樹的時候做了處理,保證建立的二叉樹是平衡二叉樹。coding utf 8 from collections import deque class node def init self,val,left non...

python 二叉樹查詢 Python二叉樹搜尋

stack depth is initialised to 0 def find in tree node,find condition,stack depth assert stack depth max stack depth deeper than max depth stack depth ...

python實現平衡二叉樹 平衡二叉樹python

stack depth is initialised to 0 def find in tree node,find condition,stack depth assert stack depth max stack depth deeper than max depth stack depth ...