题目:
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.
题意:
判断给定的二叉树是否是平衡树。
平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树的常用实现方法有红黑树、AVL、替罪羊树、Treap、伸展树等。
方法一:性能115ms
# 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 height(self, root):
if root == None:
return True
return max(self.height(root.left), self.height(root.right)) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
elif abs(self.height(root.left) - self.height(root.right)) <= 1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
return False
方法二:性能62ms
class Solution(object):
def isBalanced(self, root):
global res
res = True
def getHeight(root):
global res
if not root: return 0
leftHeight = getHeight(root.left)
if leftHeight < 0:
res = False
return -1
rightHeight = getHeight(root.right)
if rightHeight < 0 or abs(leftHeight - rightHeight) > 1:
res = False
return -1
return max(leftHeight, rightHeight) + 1
getHeight(root)
return res
第二种方法再好好看看!