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

  • Post author:
  • Post category:java


/*
 * @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




版权声明:本文为ljxzuishuai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。