题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例:
输入: root = [3,9,20,null,null,15,7]
输出: true
思路
本题的关键点在于求高度,高度是距离叶子节点的距离,所以使用后序遍历。
代码
/**
* 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 {
return getDepth(root)==-1?false:true;
};
// 递归三部曲:
// 1. 传参:根节点:root 返回值:高度或者-1
// 2. 终止条件:node==null
// 3. 单层递归逻辑:
//后序遍历左右子树高度,如果高度差 > 1,返回-1,
//如果上一次递归返回-1,直接返回-1.
//如果左右子树高度<=1,返回以该节点为根节点的子树的高度,即(左右子树高度中的最大值)
function getDepth(node: TreeNode | null): number {
if(node==null) return 0;
let leftDepth=getDepth(node.left);
let rightDepth=getDepth(node.right);
if(leftDepth==-1) return -1;
if(rightDepth==-1) return -1;
if(Math.abs( leftDepth-rightDepth)>1){
return -1;
}else{
return 1+Math.max(leftDepth,rightDepth);
}
};
总结
本题的难点还是在求二叉树高度上,理清楚二叉树高度的逻辑,本题便可迎刃而解了。如有错误之处,请大家留言指教,谢谢大家了。