"""
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 getmax(self,root):
if root == None:
return 0
else:
l = 1+self.getmax(root.left)
r = 1+self.getmax(root.right)
return max(l,r)
def isBalanced(self, root):
# write your code here
if root == None:
return True
l = self.getmax(root.left)
r = self.getmax(root.right)
if abs(l-r) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
首先要有一个 求解深度的方法,先从最大树开始判断,最后递归每一个树的左子树和右子树。 可能会从在小树当中,所以最后返回递归函数。