Content-Length: 257934 | pFad | https://github.com/Geekhyt/javascript-leetcode/issues/76

F7 110. 平衡二叉树 · Issue #76 · Geekhyt/javascript-leetcode · GitHub
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









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/Geekhyt/javascript-leetcode/issues/76

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy