【发布时间】:2021-04-08 13:54:58
【问题描述】:
在我的 AVL 树中,我决定保存以下额外信息:
当前节点的子树有多少个节点
但是我怎样才能正确地做到这一点并且在轮换时不破坏信息?
例如我的代码是:
node *tree::rotate_right(node *ptr) {
node *tmp_ptr = ptr->left_son;
ptr->left_son = tmp_ptr->right_son;
tmp_ptr->right_son = ptr;
ptr->height = std::max(height(ptr-> left_son), height(ptr-> right_son));
tmp_ptr->height = std::max(height(tmp_ptr-> left_son), height(tmp_ptr-> right_son));
return tmp_ptr;
}
node *tree::rotate_left(node *ptr) {
node *tmp_ptr = ptr->right_son;
ptr->right_son = tmp_ptr->left_son;
tmp_ptr->left_son = ptr;
ptr->height = std::max(height(ptr-> left_son), height(ptr-> right_son));
tmp_ptr->height = std::max(height(tmp_ptr-> left_son), height(tmp_ptr-> right_son));
return tmp_ptr;
}
我希望这些信息按顺序查找元素,假设在 log(n) 中找到第 i_th 个元素
例如:此处的 Select(4) 应该使用我保存的额外信息返回 5(我不是在寻求 Select 实现方面的任何帮助,而是保留这些额外数据)
【问题讨论】:
-
你在维护一个父指针吗?如果每个节点都有一个父指针,那么在每个重新平衡操作中,您都按照父指针来修复节点数。
-
欢迎来到 Stack Overflow!不要破坏你的帖子。通过在此站点上发布,您已不可撤销地授予 Stack Exchange 网络以CC BY-SA 4.0 license 分发该内容的权利,只要它认为合适即可。有关删除的替代方法,请参阅:I've thought better of my question; can I delete it?
标签: c++ algorithm tree binary-search-tree avl-tree