演算法題 19 二叉平衡樹檢查 牛客網 CC150

2022-04-22 20:51:25 字數 1794 閱讀 1092

演算法題 19 二叉平衡樹檢查 牛客網 cc150

實現乙個函式,檢查二叉樹是否平衡,平衡的定義如下,對於樹中的任意乙個結點,其兩顆子樹的高度差不超過1。

給定指向樹根結點的指標treenode*root,請返回乙個bool,代表這棵樹是否平衡。

解題**:時間複雜度為o(nlogn) n為樹中的節點數

#

-*- coding:utf-8 -*-

#class treenode:

#def __init__(self, x):

#self.val = x

#self.left = none

#self.right = none

class

balance:

defisbalance(self, root):

#write code here

ifnot

root:

return

true

heightdiff=self.getheight(root.left)-self.getheight(root.right)

if abs(heightdiff)>1:

return

false

else

:

return self.isbalance(root.left) and

self.isbalance(root.right)

defgetheight(self,root):

ifnot

root:

return

0

return max(self.getheight(root.left),self.getheight(root.right))+1

解題**二:優化版,時間複雜度為o(n),空間複雜度為o(h),h為樹的高度

#

-*- coding:utf-8 -*-

#class treenode:

#def __init__(self, x):

#self.val = x

#self.left = none

#self.right = none

class

balance:

defisbalance(self, root):

#write code here

if self.checkheight(root)==-1:

return

false

else

:

return

true

defcheckheight(self,root):

ifnot

root:

return 0 #

高度為0

leftheight=self.checkheight(root.left)

if leftheight==-1:

return -1 #

不平衡rightheight=self.checkheight(root.right)

if rightheight==-1:

return -1 #

不平衡 heightdiff=leftheight-rightheight

if abs(heightdiff)>1:

return -1

else

:

return max(leftheight,rightheight)+1

牛客網 二叉樹

如上所示,由正整數1,2,3 組成了一顆特殊二叉樹。我們已知這個二叉樹的最後乙個結點是n。現在的問題是,結點m所在的子樹中一共包括多少個結點。比如,n 12,m 3那麼上圖中的結點13,14,15以及後面的結點都是不存在的,結點m所在子樹中包括的結點有3,6,7,12,因此結點m的所在子樹中共有4個...

牛客(39)平衡二叉樹

題目描述 輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。public boolean isbalanced solution treenode root 它是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,並且左右兩個子樹都是一棵平衡二叉樹。if math.abs treedepth root...

牛客網 平衡二叉樹 解題報告 python

題目描述 輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。解題方案 這裡我取了個巧,直接用val儲存節點的層數。coding utf 8 class treenode def init self,x self.val x self.left none self.right none class sol...