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 depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,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.
// Top-Down Recursion
int helper(TreeNode* node) {
if (!node) return 0;
return max(helper(node->left), helper(node->right)) + 1;
}
bool isBalanced(TreeNode* root) { // time: O(n^2); space: O(n)
if (!root) return true;
int left = helper(root->left);
int right = helper(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
// Bottom-Up Recursion
int helper(TreeNode* node) {
if (!node) return 0;
int left = helper(node->left);
if (left == -1) return -1;
int right = helper(node->right);
if (right == -1) return -1;
if (abs(left - right) > 1) return -1;
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) { // time: O(n); space: O(n)
return helper(root) != -1;
}