Balanced Binary Tree
Example
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7Solution
"""
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]) + 1Last updated