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.
最简单的思路就是建一个height function, 可以计算每个node的height, 然后abs(left_height - right_height) <2, 再recursive 判断即可.
04/20/2019 Update : add one more solution using Divide and conquer. (add a class called returnType)
1. Constraints
1) None => True
2. Ideas
DFS T: O(n^2) optimal O(n) S; O(n)
3. Code
1) T: O(n^2)
class Solution:
def isBalance(self, root):
if not root: return True
def height(root):
if not root: return 0
return 1 + max(height(root.left) , height(root.right))
return abs(height(root.left) - height(root.right)) < 2 and self.isBalance(root.left) and self.isBalance(root.right)
2) T: O(n) S; O(n)
bottom to up, 一旦发现不符合的,就不遍历, 直接返回-1一直到root, 所以不需要每次来计算node的height.
class Solution:
def isBalance(self, root):
def height(root):
if not root: return 0
l, r = height(root.left), height(root.right)
if -1 in [l, r] or abs(l-r) >1: return -1
return 1 + max(l,r)
return height(root) != -1
3) T: O(n) . S: O(n)
class ResultType:
def __init__(self, isBalanced, height):
self.isBalanced = isBalanced
self.height = height class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def helper(root):
if not root:
return returnType(True, 0)
left = helper(root.left)
right = helper(root.right)
if not left.isBalanced or not right.isBalanced or abs(left.height - right.height) > 1:
return ResultType(False, 0)
return ResultType(True, 1 + max(left.height, right.height))
return helper(root).isBalanced