平衡二叉树

2019-11-14  本文已影响0人  ElricTang

《剑指offer》刷题笔记。如有更好解法,欢迎留言。

关键字: 树的深度 平衡二叉树

题目描述:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:

function depth(root){
    let lh,rl,h;
    if(root === null)return 0;
    lh = depth(root.left);
    rh = depth(root.right);
    if(lh >= rh){
        h = lh+1;
    }
    else{
        h = rh+1;
    }
    return h;
}
function IsBalanced_Solution(pRoot)
{
    if(pRoot === null)return true;
    let gap = depth(pRoot.left) - depth(pRoot.right);
    if(gap > 1 || gap < -1){
        return false;
    }
    return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
}
上一篇 下一篇

猜你喜欢

热点阅读