leetcode 算法题110 (简单026) 平衡二叉树
- 题目介绍
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
- 示例
给定二叉树 [3,9,20,null,null,15,7] 返回 true 。
3 / \ 9 20 / \ 15 7
给定二叉树 [1,2,2,3,3,null,null,4,4]返回 false 。
1 / \ 2 2 / \ 3 3 / \ 4 4
- 解法一
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
if(!root) {
return true;
}
let leftDepth = getMaxDepth(root.left, 0);
let rightDepth = getMaxDepth(root.right, 0);
return Math.abs(leftDepth - rightDepth) <= 1 && isBalanced(root.left) && isBalanced(root.right);
};
const getMaxDepth = (node, depth) => {
if (node) {
return Math.max(getMaxDepth(node.left, depth + 1), getMaxDepth(node.right, depth + 1));
}
return depth;
}
执行用时 : 92 ms, 在所有 JavaScript 提交中击败了93,89%的用户
内存消耗 : 37.5MB, 在所有 JavaScript 提交中击败了48.51%的用户