Balanced Tree Check
A binary tree is height-balanced if, for every node in the tree, the difference in heights of the left and right subtrees is no more than 1.
Approach:
We use a post-order traversal where, at each node, we first calculate the heights of the left and right subtrees, check the balance condition, and then propagate the height upwards. This ensures that we check each node only once, achieving a linear time complexity.
The function solve(Node* root) returns a pair:
pair<bool, int>solve(Node* root){
if(root == NULL){
pair<bool,int>p = make_pair(true, 0);
return p;
}
pair<bool, int>left = solve(root->left);
pair<bool, int>right = solve(root->right);
bool condn = abs(left.second - right.second) <= 1;
pair<bool, int>ans;
ans.second = max(left.second, right.second) + 1;
if(left.first && right.first && condn){
ans.first = true;
ans.second = max(left.second, right.second) + 1;
}
else{
ans.first = false;
}
return ans;
}
bool isBalanced(Node *root)
{
return solve(root).first;
}
领英推荐
Explanation:
Time Complexity: O(N)
Space Complexity: O(H)
Student || 3??Codechef (Max rating -1629) || 5?? C++/Problem Solving Hackerrank ||Codeforces Max Rating -1166|| CP Enthusiast || Problem Solver & Daily Streak Gold??Codechef || 300+Codechef || 200+ Codeforces
5 个月Interesting