原题
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.
解法1
递归, 定义depth函数计算节点的高度, 比较每个子树的高度差是否大于1, 如果是则返回False.
Worst case: O(n) + 1/2 * O(n/2) + 1/4 * O(n/4) + …
Time: O(n*log(n))
Space: O(1)
代码
# 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
left_depth = self.depth(root.left)
right_depth = self.depth(root.right)
if abs(left_depth - right_depth) <= 1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
return False
def depth(self, node):
if not node:
return 0
return max(self.depth(node.left), self.depth(node.right)) + 1
解法2
一次遍历, 定义depth函数, 如果左子树或右子树的是不平衡的, 或者它们的高度差大于1, 则返回-1, 代表不平衡, 否则继续往下搜索. 最终我们检查depth的函数是否为-1
Time: O(n)
Space: O(1)
代码
# 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 depth(root):
# base case
if not root: return 0
left_depth = depth(root.left)
right_depth = depth(root.right)
if left_depth == -1 or right_depth == -1 or abs(left_depth- right_depth) > 1:
return -1
return max(left_depth, right_depth) + 1
return depth(root) != -1