[英]C++ Improved efficiency to check if a BST is height balanced?
我正在尝试实现一个 function isOk(Node*, int&)
来检查 BST 的每个节点是否遵循以下属性:
- 其左右子树的高度最多可以相差 1 级。
一个例子可能是:
这是我写的 function:
bool isOk(Node* tree, int& maxH)
{
//if leaf, property is respected
if(!tree->left_ && !tree->right_) return true;
//otherwise
int hL = 0;
int hR = 0;
bool propL = isOk(tree->left_, hL);
bool propR = isOk(tree->right_, hR);
if(propL) hL++;
if(propR) hR++;
if(hL - hR => -1 && hL - hR <= 1) {
maxH = max(hL, hR);
return true;
}
else return false;
}
我们假设结构节点是这样的:
struct Node
{
Node* left_;
Node* right_;
int label_;
//no constructor or destructor, this is not the focus
};
最初我写了这部分:
/*...*/
int hL = 0;
int hR = 0;
bool propL = isOk(tree->left_, hL);
bool propR = isOk(tree->right_, hR);
if(propL) hL++;
if(propR) hR++;
/*...*/
通过以下方式:
int hL = height(tree->left_);
int hR = height(tree->right_);
bool propL = isOk(tree->left_, hL);
bool propR = isOk(tree->right_, hR);
其中 function height(Node*)
为:
int height( Node* tree)
{
if(tree== NULL) return 0;
int leftH = 0;
int rightH = 0;
leftH = height(tree->left_);
rightH = height(tree->right_);
return 1 + max(leftH, rightH);
}
现在,如果我没记错的话, height
的复杂度应该是 O(n)。 所以,如果在我的isOk
function 中使用它,它的整体复杂性应该会大大增加,对吧?
也就是说,我试图跟踪每次调用isOk
时每次hL
和hR
递增的每个子树的高度。
这是我做错了什么吗? 请在我错的地方纠正我。
谢谢!
可以让isOk
返回一个pair<bool, int>
,其中bool
表示返回此值的节点是否遵循所述属性,而int
表示它在树中的高度。
假设pair<boor, int> propL, propR
分别是当前节点的左右孩子返回的值,那么当前节点将满足上述属性iff propL->first == true && propR->first == true && (int)abs(propL->second-propR->second) <= 1
。 然后这个值连同当前节点的高度(等于max(propL->second, propR->second) + 1
)将返回给当前节点的父节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.