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. 平衡二叉树 #76

Open
Geekhyt opened this issue Sep 19, 2021 · 0 comments
Open

110. 平衡二叉树 #76

Geekhyt opened this issue Sep 19, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 19, 2021

原题链接

一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过 1。

  1. 如果遍历完成,还没有高度差超过 1 的左右子树,则符合条件
  2. 判断左右子树高度差,超过 1 则返回 false
  3. 递归左右子树
  4. 封装获取子树高度函数 getHeight
const isBalanced = function(root) {
    if (!root) return true

    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
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
@Geekhyt Geekhyt added the 简单 label Sep 19, 2021
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