假设我有两个 AVL 树,并且第一棵树中的每个元素都小于第二棵树中的任何元素.将它们连接成一棵 AVL 树的最有效方法是什么?我到处搜索,但没有找到任何有用的东西.
Assume that I have two AVL trees and that each element from the first tree is smaller then any element from the second tree. What is the most efficient way to concatenate them into one single AVL tree? I've searched everywhere but haven't found anything useful.
假设您可能会破坏输入树:
Assuming you may destroy the input trees:
因此,整个操作可以在 O(log n) 中执行.
Thus, the entire operation can be performed in O(log n).
再想一想,在以下算法中更容易推理旋转.它也很可能更快:
On second thought, it is easier to reason about the rotations in the following algorithm. It is also quite likely faster:
left
树中移除最右边的元素(如有必要,旋转并调整其计算高度).让 n
成为那个元素.O(log n)left
高 1.让 r
成为那个节点.O(log n)用值为 n 的新节点以及子树 left
和 r
替换该节点.O(1)
通过构造,新节点是 AVL 平衡的,其子树 1 比 r
高.
left
tree (rotating and adjusting its computed height if necessary). Let n
be that element. O(log n)left
. Let r
be that node. O(log n)replace that node with a new node with value n, and subtrees left
and r
. O(1)
By construction, the new node is AVL-balanced, and its subtree 1 taller than r
.
相应地增加其父级的余额.O(1)
increment its parent's balance accordingly. O(1)
这篇关于连接/合并/加入两个 AVL 树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!