Skip to content

110. 平衡二叉树 #76

@Geekhyt

Description

@Geekhyt

原题链接

一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy