# 110. Balanced Binary Tree
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]:
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.
# Solution
Approach 1: Recursion. To avoid the tricky case that a result is determined by 2 separate things (left and right's balance and their depth), we can use -1 to represent the "depth" when the node is not balanced.
# Code (Python)
Approach 1:
def isBalanced(self, root):
return self._helper(root) != -1
def _helper(self, node):
if not node:
return 0
left, right = self._helper(node.left), self._helper(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
# Code (C++)
Approach 1:
/**
* 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 isBalanced(root, height);
}
private:
bool isBalanced(TreeNode *root, int& height)
{
if (root == NULL) return true;
int leftHeight = 0;
int rightHeight = 0;
bool leftIsBalanced = isBalanced(root->left, leftHeight);
bool rightIsBalanced = isBalanced(root->right, rightHeight);
height = std::max(leftHeight, rightHeight) + 1;
if (leftIsBalanced && rightIsBalanced && abs(leftHeight - rightHeight) <= 1)
return true;
return false;
}
};