leetcode-判断是否为平衡树-javascript实现

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return bool布尔型
  */
function depth(root)
{
    if(!root)
    {
        return 0;
    }else if(!(root.left)&&!(root.right)){
        return 1;
    }else{
        return Math.max(depth(root.left),depth(root.right)) +1;
    }
}
function isBalanced( root ) {
    // write code here
            if(!root){
                return true;
            }else{
                return (Math.abs(depth(root.left)-depth(root.right))<2) && isBalanced(root.left) && isBalanced(root.right);
            }
}
module.exports = {
    isBalanced : isBalanced
};

猜你喜欢

转载自blog.csdn.net/qq_42099097/article/details/107318401
今日推荐