题目
思路
拆解子问题。
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def balance(self, root):
if not root:
return True, 0
leftBool, leftHeight = self.balance(root.left)
rightBool, rightHeight = self.balance(root.right)
resBool = False
if leftBool and rightBool:
if abs(leftHeight - rightHeight) < 2:
resBool = True
return resBool, max(leftHeight, rightHeight) + 1
def isBalanced(self, root):
# write your code here
return self.balance(root)[0]