
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
# 分情况
# 左右两颗子树有不同时为平衡二叉树返回false
if not self.isBalanced(root.left) or not self.isBalanced(root.right):
return False
# 每个节点的左右结点高度差大于1时返回false
elif abs(self.depth(root.left)-self.depth(root.right)) > 1:
return False
return True
def depth(self, root):
# 求节点深度
if not root:
return -1
else:
return max(self.depth(root.left), self.depth(root.right)) + 1版权声明:本文为ziqingnian原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。