pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.35k stars 243 forks source link

平衡二叉树 #1039

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

110. 平衡二叉树

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    if(root == null)
        return true;
    if(Math.abs(height(root.left) - height(root.right)) > 1) {
        return false;
    }
    return isBalanced(root.left) && isBalanced(root.right)
};
function height(root) {
    if(root == null)
        return 0;
    return Math.max.call(undefined, height(root.left) + 1, height(root.right) + 1);
}