LeetCode 题解工作台
平衡二叉树
给定一个二叉树,判断它是否是 平衡二叉树 示例 1: 输入: root = [3,9,20,null,null,15,7] 输出: true 示例 2: 输入: root = [1,2,2,3,3,null,null,4,4] 输出: false 示例 3: 输入: root = [] 输出: tr…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
定义函数 计算二叉树的高度,处理逻辑如下: - 如果二叉树 为空,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个二叉树,判断它是否是 平衡二叉树
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4] 输出:false
示例 3:
输入:root = [] 输出:true
提示:
- 树中的节点数在范围
[0, 5000]内 -104 <= Node.val <= 104
解题思路
方法一:自底向上的递归
定义函数 计算二叉树的高度,处理逻辑如下:
- 如果二叉树 为空,返回 。
- 否则,递归计算左右子树的高度,分别为 和 。如果 或 为 ,或者 和 的差的绝对值大于 ,则返回 ,否则返回 。
那么,如果函数 返回的是 ,则说明二叉树 不是平衡二叉树,否则是平衡二叉树。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if root is None:
return 0
l, r = height(root.left), height(root.right)
if l == -1 or r == -1 or abs(l - r) > 1:
return -1
return 1 + max(l, r)
return height(root) >= 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand the difference between balanced and unbalanced trees?
- question_mark
Can you explain how DFS helps in both height calculation and detecting imbalances?
- question_mark
Will you handle edge cases like an empty tree or a skewed tree efficiently?
常见陷阱
外企场景- error
Not handling edge cases like an empty tree, which should return true.
- error
Missing the early termination by not checking imbalance during traversal, leading to unnecessary work.
- error
Incorrectly calculating the height of subtrees, which can cause false results in balance checking.
进阶变体
外企场景- arrow_right_alt
Check if the tree is a full binary tree.
- arrow_right_alt
Find the diameter of the tree, which is the longest path between any two nodes.
- arrow_right_alt
Determine if a binary tree is perfect, meaning all leaf nodes are at the same level and every parent has two children.