Leetcode 110. Balanced Binary Tree
Leetcode Problem 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:
3
/ \
9 20
/ \
15 7
Return true
.
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false
.
To determine if a binary tree is balanced, you need to check the height of each subtree and ensure the difference in height is no more than 1 for any node. A common way to solve this is through a combination of depth-first traversal and height calculation:
height
that computes the height of each subtree. If an imbalance is detected, return an error code (e.g., -1).null
, return 0 (height of empty subtree).#include <iostream>
#include <algorithm>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), right(right) {}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
return checkHeight(root) != -1;
}
private:
int checkHeight(TreeNode* node) {
if (!node) {
return 0; // A null node is balanced with height 0
}
int leftHeight = checkHeight(node->left);
int rightHeight = checkHeight(node->right);
// If the left or right subtree is unbalanced, propagate the failure upwards
if (leftHeight == -1 || rightHeight == -1) {
return -1;
}
// If the height difference is more than 1, mark this node as unbalanced
if (std::abs(leftHeight - rightHeight) > 1) {
return -1;
}
// Return the height of the subtree rooted at this node
return std::max(leftHeight, rightHeight) + 1;
}
};
This approach checks both the height and balance of the subtrees efficiently in a single traversal.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?