刷题笔录
作者:关注了🐴
Github:Github
掘金:进去看看🐴
爱好:Americano More Ice !
QQ学习交流群(new): 811792998
剑指Offer - 平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
解题
从顶至底:先序遍历
+ 计算深度
- 时间复杂度 O(Nlog N): 最差情况下, “满二叉树” 遍历
- 空间复杂度 O(N) : 最差情况下(树退化为链表时),递归 O(N) 的栈空间
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root: return True
# 差值绝对值<=1 & 左子树平衡 & 右子树平衡
return abs(self.depth(root.left) - self.depth(root.right)) <= 1 and \
self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, root):
if not root: return 0
# 最大深度计算
return max(self.depth(root.left), self.depth(root.right)) + 1