Skip to content

Commit

Permalink
110. 平衡二叉树
Browse files Browse the repository at this point in the history
  • Loading branch information
cslc-ubm committed Jul 12, 2021
1 parent a38b7bc commit ddf4265
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions 110. 平衡二叉树.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* 给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
*/

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
* 时间复杂度 O(n),空间复杂度 O(n)
*/
var isBalanced = function (root) {
return balanced(root) !== -1
}

function balanced(node) {
if (!node) return 0
const left = balanced(node.left)
const right = balanced(node.right)
if (left === -1 || right === -1 || Math.abs(left - right) > 1) {
return -1
}
return Math.max(left, right) + 1
}

0 comments on commit ddf4265

Please sign in to comment.