题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树(不考虑其是不是排序二叉树,只需要考虑其平衡性)。
分析:首先,平衡二叉树的平衡性即,左子树与右子树的高度差的绝对值不大于1。即在遍历二叉树节点的过程中需要求该节点的左子树和右子树的高度差,自底向上的递归求树高度更为简单。
求解:
// 深度计算法
function isBalanced<T>(root: TreeNode<T> | null): boolean {
if (root === null) return true;
const leftTree = root.left;
const rightTree = root.right;
// 左右子树高度差大于1,不平衡
if (Math.abs(maxDepth1(leftTree) - maxDepth1(rightTree)) > 1) return false;
// 否则取决于左子树与右子树分别是否平衡
return isBalanced(leftTree) && isBalanced(rightTree);
}
// 自底向上递归法,
export function maxDepth1<T>(root: TreeNode<T> | null): number {
if (root === null) return 0;
const left = root.left;
const right = root.right;
return 1 + Math.max(maxDepth1(left), maxDepth1(right));
}