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 判断即可.
扫描二维码关注公众号,回复:
2592487 查看本文章
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