题目
题目链接
题目描述:输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
思路
递归判断左右子树的深度差,并设计辅助函数计算深度。
复杂度
- 时间复杂度: O(n^2)
- 空间复杂度: O(n)
代码
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
// 判断是否平衡
function isBalanced(root: TreeNode | null): boolean {
if (root === null) return true;
const leftDepth = getDepth(root.left);
const rightDepth = getDepth(root.right);
const diff = Math.abs(leftDepth - rightDepth);
return diff <= 1 && isBalanced(root.left) && isBalanced(root.right);
};
// 辅助函数,获取树的深度
function getDepth(root: TreeNode | null): number {
if (root === null) return 0;
return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
}
674

被折叠的 条评论
为什么被折叠?



