Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

110. 平衡二叉树 #30

Open
pigpigever opened this issue Dec 19, 2019 · 0 comments
Open

110. 平衡二叉树 #30

pigpigever opened this issue Dec 19, 2019 · 0 comments
Labels
二叉树 递归 递归类型的算法题

Comments

@pigpigever
Copy link
Owner

pigpigever commented Dec 19, 2019

题目描述

给定一个二叉树,判断它是否是高度平衡的二叉树。

题目剖析

平衡二叉树的定义是:

一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。

所以,我们要判断每个节点的左右子树是否是平衡二叉树,这个过程可以递归的进行

示例代码

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    // 遍历到底还没有发现高度差超过 1 的左右子树,那么这个子树肯定符合平衡二叉树的规范
    if (!root) {
        return true
    }
    // 判断左右子树的高度差,如果超过 1 那么立即返回 false
    if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1) {
        return false
    }
    // 分别递归左右子树
    return isBalanced(root.left) && isBalanced(root.right)
    // 获取某个子树的高度
    function getHeight (root) {
        if (!root) {
            return 0
        }
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1
    }
};
@pigpigever pigpigever added 递归 递归类型的算法题 二叉树 labels Dec 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
二叉树 递归 递归类型的算法题
Projects
None yet
Development

No branches or pull requests

1 participant