原文链接:
读题:
判断是否为平衡二叉树,平衡二叉树的定义是每个节点的左右子树的高度差不超过1,显然需要通过求高度,也就是树的深度差来判断。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
lengthL = self.maxDepth(root.left)
lengthR = self.maxDepth(root.right)
if lengthL > lengthR + 1 or lengthR > lengthL + 1:
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)