GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — 平衡二叉树-110 · Issue #56 · sl1673495/leetcode-javascript

平衡二叉树-110 #56

New issue
Copy link
New issue
Copy link
Open
Open
平衡二叉树-110#56
Copy link
Labels
DFS深度优先遍历深度优先遍历二叉树

Description

@sl1673495
sl1673495
opened on Jun 6, 2020
Issue body actions

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

本题中,一棵高度平衡二叉树定义为:

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

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7
返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

首先定义一个辅助函数 getHeight 用于获取二叉树某个节点的高度,只需要递归即可:

function getHeight(node) {
    if (!node) return 0
    return Math.max(getHeight(node.left), getHeight(node.right)) + 1
}

之后是否平衡就比较好求了,首先比较直接子节点 left 和 right 是否高度相差绝对值 <= 1,之后再递归的比较 left 和 right 是否是平衡二叉树即可。

var isBalanced = function (root) {
    if (!root) {
        return true
    }

    let isSonBalnaced = Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1

    return isSonBalnaced && isBalanced(root.left) && isBalanced(root.right)
};

Activity

  1. sl1673495
    added
    DFS深度优先遍历深度优先遍历
    二叉树
    on Jun 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DFS深度优先遍历深度优先遍历二叉树

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402520 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.