Balanced Binary Tree
题目描述
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.
解题方法
这一题也是用recursive的方法做
- 对于每一个root,分别get左右两边子树的max depth
- 如果balanced,就继续recursive的检查左右子树
Solution
# 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 isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
leftDepth = self.getDepth(root.left)
rightDepth = self.getDepth(root.right)
diff = abs(leftDepth - rightDepth)
if diff > 1:
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
def getDepth(self, root):
if not root:
return 0
return 1 + max(self.getDepth(root.left), self.getDepth(root.right))