编程语言
首页 > 编程语言> > LC-平衡二叉树(JavaScript实现)

LC-平衡二叉树(JavaScript实现)

作者:互联网

/*
 * @lc app=leetcode.cn id=110 lang=javascript
 *
 * [110] 平衡二叉树
 */

// @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)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    //先计算高度
    let getHeight = root => {
        if(!root) return 0;
        return Math.max(getHeight(root.left),getHeight(root.right))+1;
    }
    //自定义abs
    let abs = (a,b) => {
        return (a-b)>=0?(a-b):(b-a);
    }
    if(!root) return true;
    return abs(getHeight(root.left),getHeight(root.right)) <=1 && isBalanced(root.left) && isBalanced(root.right)
    
};
// @lc code=end


标签:right,return,LC,val,JavaScript,getHeight,二叉树,root,left
来源: https://blog.csdn.net/ljxzuishuai/article/details/122796326