Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
Runtime: 16 ms, faster than 56.86% of C++ online submissions for Balanced Binary Tree.
Memory Usage: 16.5 MB, less than 100.00% of C++ online submissions for Balanced Binary Tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height = 0;
return check(root, height);
}
bool check(TreeNode *root, int& height) {
if (root == NULL) {
height = 0;
return true;
}
int leftHeight = 0;
int rightHeight = 0;
if (!check(root->left, leftHeight)) {
return false;
}
if (!check(root->right, rightHeight)) {
return false;
}
if (abs(leftHeight - rightHeight) > 1) {
return false;
}
height = max(leftHeight, rightHeight) + 1;
return true;
}
};
Runtime: 88 ms, faster than 85.22% of JavaScript online submissions for Balanced Binary Tree.
Memory Usage: 43.2 MB, less than 41.05% of JavaScript online submissions for Balanced Binary Tree.
/**
* 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}
*/
var isBalanced = function(root) {
function getDepth(node) {
if (!node) {
return 0;
}
const left = getDepth(node.left);
if (left === -1) {
return -1;
}
const right = getDepth(node.right);
if (right === -1) {
return -1;
}
const dis = Math.abs(left - right);
return dis <= 1 ? Math.max(left, right) + 1 : -1;
}
return getDepth(root) !== -1;
};