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 #56

Open
sl1673495 opened this issue Jun 6, 2020 · 0 comments
Open

平衡二叉树-110 #56

sl1673495 opened this issue Jun 6, 2020 · 0 comments
Labels
DFS 深度优先遍历 二叉树

Comments

@sl1673495
Copy link
Owner

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

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

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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
}

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

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)
};
@sl1673495 sl1673495 added DFS 深度优先遍历 二叉树 labels Jun 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 深度优先遍历 二叉树
Projects
None yet
Development

No branches or pull requests

1 participant