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 ofevery node never differ by more than 1.
Just follow the definition.....
static int getDepth(TreeNode* root) {
if(!root) return 0;
return 1 + max(getDepth(root->left), getDepth(root->right));
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
return abs(leftDepth - rightDepth) <= 1 && isBalanced(root->right) && isBalanced(root->left);
}
For a better performance. It is good to build a data structure. To traversal the tree in bottom up order which might help to end the program earlier once detected unbalanced.
/*
Build a structure
*/
class BalanceStatsWithHeight {
bool balanced;
int height;
}
BalanceStatsWithHeight checkBalanceTree(TreeNode* root) {
if(!root) return {true, -1};
auto left_tree = checkBalanceTree(root->left);
if(!left_tree.balanced) return {false, 0};
auto right_tree = checkBalanceTree(root->right);
if(!right_tree.balanced) return {false, 0};
bool is_balance = abs(left_tree.height - right_tree.height) <= 1;
int curr_height = max(left_tree.height, right_tree.height) + 1;
return {is_balance, curr_height};
}