-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |