- 分类:Tree/DFS
- 时间复杂度: O(nlogn)/O(n)
110. 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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
代码:
O(nlogn)方法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root==None:
return True
h_left=self.height(root.left)
h_right=self.height(root.right)
return abs(h_left-h_right)<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
def height(self, root):
if root==None:
return 0
else:
return max(self.height(root.left),self.height(root.right))+1
O(n)方法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root==None:
return True
def height(root):
if root==None:
return 0
h_l=height(root.left)
h_r=height(root.right)
if h_l==-1 or h_r==-1 or abs(h_l-h_r)>1:
return -1
else:
return max(h_l,h_r)+1
return height(root)!=-1
讨论:
1.经典平衡2叉树,用DFS解(也是递归orz)
2.第一种O(nlogn)的方法好解释
3.第二种O(n)的方法是直接检测高度,当高度差>1的时候直接返回-1,直接返回-1到最终,速度快。