我在下面实现了一段 C++ 代码,用于检查二叉树是否平衡,即左右子树的高度最多相差 1。但是,我不确定它是否有效,或者反复检查子树不好的方式。有人可以指导我吗?
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);
}