Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example
Given binary tree A = {3,9,20,#,#,15,7}, B = {3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7
The binary tree A is a height-balanced binary tree, but B is not.
Solution
"""
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 isBalanced(self, root):
# write your code here
return self.maxDepth(root) != -1
def maxDepth(self, root):
if root == None:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
if left == -1 or right == -1 or abs(left - right) > 1: # set up -1 is False
return -1
return max(left, right) + 1
#也可以直接使用多参数返回形式。
def maxDepth(self, root):
if root == None:
return True, 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
if left[0] == False or right[0] == False or abs(left[1] - right[1]) > 1:
return False, 0
return True, max(left[1], right[1]) + 1