1. Top-Down Height Comparison
Intuition
Compute height(left) and height(right). If difference > 1, return false. Otherwise return isBalanced(left) && isBalanced(right).
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return true.
- Step 2: lh = height(root.left), rh = height(root.right).
- Step 3: If abs(lh - rh) > 1 return false.
- Step 4: Return isBalanced(root.left) && isBalanced(root.right).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int height(TreeNode* node) { if (!node) return 0; return 1 + max(height(node->left), height(node->right)); } bool isBalanced(TreeNode* root) { if (!root) return true; int lh = height(root->left); int rh = height(root->right); if (abs(lh - rh) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^2)— Repeated height computation takes O(n2) worst case on skewed trees. - Space complexity:
O(h)— Call stack takes O(h) space.