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 ofeverynode never differ by more than 1.
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.
这一题也是用recursive的方法做
对于每一个root,分别get左右两边子树的max depth
如果balanced,就继续recursive的检查左右子树
时间复杂度为O(NlgN)
# 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
if abs(self.depth(root.left)-self.depth(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, root):
if not root:
return 0
return 1+max(self.depth(root.left),self.depth(root.right))
上面那个方法正确但不是很高效,因为每一个点都会被上面的点计算深度时访问一次,我们可以进行优化。方法是如果我们发现子树不平衡,则不计算具体的深度,而是直接返回-1。那么优化后的方法为:对于每一个节点,我们通过check方法递归获得左右子树的深度,如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1,此方法时间复杂度O(N),空间复杂度O(H),参见代码如下:
https://www.youtube.com/watch?v=TWDigbwxuB4
# 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
"""
def check(root):
if not root:
return 0
leftnode = check(root.left)
if leftnode == -1:
return -1
rightnode = check(root.right)
if rightnode == -1:
return -1
if abs(leftnode - rightnode)>1:
return -1
return 1+max(leftnode,rightnode)
return check(root) != -1
PreviousLowest Common Ancestor of a Binary Search TreeNextConvert Sorted Array to Binary Search Tree
Last updated
Was this helpful?