python实现检查平衡性算法
采用递归方法实现
第一种采用两次递归法,时间复杂度较高,效率低
代码如下
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
def get(root):
if not root:
return 0
a=get(root.left)
b=get(root.right)
return max(a,b)+1
if abs(get(root.left)-get(root.right))>1:
return False
return self.isBalanced(root.left)&self.isBalanced(root.right)
第二种方法只递归自己定义的函数
代码如下
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def get(root):
if not root:
return 0
a=get(root.left)
b=get(root.right)
if a=='False' or b=='False':
return 'False'
if abs(a-b)>1:
return 'False'
return max(a,b)+1
ans=get(root)
if ans=='False':
return False
else:
return True