题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题目中平衡二叉树的定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
题目分析
同理适用递归方案,进行递归分析
1、 函数意义:获取当前二叉树的高度
2、 边界条件: 二叉树为空
3、递归过程: 将二叉树的节点分别传入高度方法中求出节点的高度,同时进行改造,左边高度与右边高度相减大于1则不是平衡树,否则就为平衡树
代码实现
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
const getHeight = (root) => {
if (!root) return 0;
const l = getHeight(root.left);
const r = getHeight(root.right);
if (l < 0 || r < 0) return -2;
if (Math.abs(l - r) > 1) return -2;
return Math.max(l, r) + 1;
};
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function (root) {
return getHeight(root) >= 0;
};
// @lc code=end