39-平衡二叉树

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

平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
//缺点:节点重复遍历,影响效率
function IsBalanced_Solution(pRoot)
{
    // write code here
    if(pRoot == null) return true;
    var left = treeDepth(pRoot.left);
    var right = treeDepth(pRoot.right);
    return Math.abs(right - left) <= 1 && IsBalanced_Solution(pRoot.left) 
    && IsBalanced_Solution(pRoot.right)
}

function treeDepth(root) {
    if(!root) return 0;
    var left = treeDepth(root.left);
    var right = treeDepth(root.right);
    return Math.max(left, right) + 1;
}
//在求高度的同时判断是否平衡,如果不平衡就返回-1,否则返回树的高度。
//并且当左子树高度为-1时,就没必要去求右子树的高度了,可以直接一路返回到最上层了
/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function IsBalanced_Solution(pRoot)
{
    // write code here
    return getDepth(pRoot) != -1
}
function getDepth(root) {
    if(root == null) return 0;
    var left = getDepth(root.left);
    if(left == -1) return -1;
    var right = getDepth(root.right);
    if(right == -1) return -1;
    return Math.abs(right - left) > 1 ? -1 : 1 + Math.max(left, right);
}
发布了81 篇原创文章 · 获赞 0 · 访问量 1982

猜你喜欢

转载自blog.csdn.net/weixin_43655631/article/details/104058750