I implemented the C++ piece of code below, to check if a binary tree is balanced, i.e. the height of the left and right subtrees differ by at most 1. However, I am not sure if it is efficient, or repeatedly checks subtrees in a bad way. Can someone guide me please?
unordered_map <Node*, int> height;
struct Node{
int key;
Node* left;
Node* right;
}
bool isBalanced(Node* root){
if (root == nullptr){
height[root] = -1;
return true;
}
if (!isBalanced(root->left)) return false;
if (!isBalanced(root->right)) return false;
height[root] = max(height[root->left], height[root->right]) + 1;
return (abs(height[root->left] - height[root->right]) < 1);
}
isBalanced
to returnint
, -1 for unbalanced or depth otherwise. Then you do not need additional map – Slava