题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
class Solution: def IsBalanced_Solution(self , pRoot: TreeNode) -> bool: if not pRoot: # 如果为空,则返回true return True def depth(root): # 定义一个求深度的函数 if not root: return 0 dl = depth(root.left) dr = depth(root.right) return max(dl, dr) + 1 def judge(root): # 定义一个利用左右子树深度差判断是否为平衡二叉树的函数 l = depth(root.left) #之前已经考虑了节点为空的情况,此处不再考虑 r = depth(root.right) c = l - r if c > 1 or c < -1: # 递归出口一,子树高度差大于1,返回false return False elif l == 0 or r == 0:# 递归出口二,高度差不大于1的情况下, return True # 如果某一子树高度为0,则返回true else: return judge(root.left) and judge(root.right) # 不满足前两个条件则递归比较子节点 # 返回值用and连接判断 return judge(pRoot)
