题解 | #36.判断是不是平衡二叉树#

判断是不是平衡二叉树

http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

先求出每一个结点的高度->getHeight(root)

递归地判断是否为平衡二叉树->isBalanced(root)

function IsBalanced_Solution(pRoot)
{
  function getHeight(root){
    if(root == null)  return 0;
    root.height = Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    return root.height;
  }
  function isBalanced(root){
    if(root == null)
      return true;
    if(root.left==null && root.right==null)
      return true;
    if(root.left==null)
      return root.right.height<=1 && isBalanced(root.right);
    if(root.right==null)
      return root.left.height<=1 && isBalanced(root.left);
    
    return Math.abs( root.left.height - root.right.height ) <=1 && isBalanced(root.left) && isBalanced(root.right);
  }
  getHeight(pRoot);
  return isBalanced(pRoot);
  
}
module.exports = {
    IsBalanced_Solution : IsBalanced_Solution
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:29
点赞 评论 收藏
分享
星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务