我实现了下面这段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);
}
isBalanced
函数返回一个整数类型int
,返回值为 -1 表示不平衡,否则返回深度。这样你就无需额外使用字典结构。 - Slava