Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在自平衡树中保存额外信息?_C++_Algorithm_Tree_Binary Search Tree_Avl Tree - Fatal编程技术网

C++ 在自平衡树中保存额外信息?

C++ 在自平衡树中保存额外信息?,c++,algorithm,tree,binary-search-tree,avl-tree,C++,Algorithm,Tree,Binary Search Tree,Avl Tree,在我的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

在我的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个元素

例如:Select(4)在这里应该使用我保存的额外信息返回5(我不是在寻求Select实现方面的任何帮助,而是在保留额外数据方面)


通常的方法是只跟踪剩余子节点的数量(加上作为锚节点一部分的节点总数)。然后,只要当前节点的计数小于所需的偏移量,就可以在任意特定偏移量处查找节点。如果在任何一点上,父节点的计数更大,则从偏移量中减去当前节点的计数,然后沿着节点的右侧向下移动


在左旋转过程中,您将前一个父级的计数添加到右子级的计数中,在右旋转过程中,您将从前一个父级的计数中减去左一个子级的计数。

您是否维护父级指针?如果每个节点都有一个父指针,那么在每次重新平衡操作中,您都会跟随父指针来修复节点计数。欢迎使用堆栈溢出!不要破坏你的帖子。通过在此网站上发布,您已不可撤销地授予Stack Exchange network在其认为合适的时间内根据发布该内容的权利。有关删除的替代方案,请参见: