题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
python3,递归
class Solution: def IsBalanced_Solution(self , pRoot: TreeNode) -> bool: def depth(root): if not root: return 0 a = 1 + depth(root.left) b = 1 + depth(root.right) return max(a, b) # 空树返回True。各个子树只要有深度差大于1/小于-1的,返回False。否则(and连接)返回True。 return bool(not pRoot) or ((False if ((depth(pRoot.left) - depth(pRoot.right)) > 1 or (depth(pRoot.left) - depth(pRoot.right)) < -1) else True) and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right))