Balanced Binary Tree:
1. The left and right subtree’s height differ by at most one, AND
2. The left subtree is balanced, AND
3. The right subtree is balance.
According to above definition, we have both O(nlogn) and O(n) method to solve this problem.
O(nlogn): this method touched all nodes in BT.
int getHeight(TreeNode* root){
if(!root) return 0;
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
bool isBalanced(TreeNode* root){
if(!root) return true;
int diff = abs(getHeight(root->left) - getHeight(root->right));
if(diff > 1) return false;
else return isBalanced(root->left) && isBalanced(root->right);
}
O(n):
int checkHeight(TreeNode* root){
if(!root) return 0;
int left = checkHeight(root->left);
if(left == -1) return -1;
int right = checkHeight(root->right);
if(right == -1) return -1;
int diff = abs(left - right);
if(diff > 1) return -1;
else return max(left,right) + 1;
}
bool isBalanced(TreeNode* root){
if(checkHeight(root) == -1) return false;
else return true;
}
bool isBalancedHepler(TreeNode* root, int& depth){
if(!root) {
depth = 0;
return true;
}
int left, right;
// Notice, the logic operation is shortcut
// once the left tree is judged to be unbalanced, then the right tree will not be judged
if(isBalancedHepler(root->left, left) && isBalancedHepler(root->right, right) && abs(left - right)<2){
depth = max(left,right) + 1;
return true;
}
else return false;
}
bool isBalanced(TreeNode *root) {
// write your code here
int height;
return isBalancedHepler(root, height);
}