複雑度


9

分割操作は、複雑度 AVLツリーに実装できますO(logn)か?このトピックに関する記事または特定の情報へのリンクに興味があります。

分割操作は、キーに基づいて、AVLツリーを2つの派生AVLツリーに分割します。派生したツリーの1つは、すべてのキーが元のキーよりも小さいすべての頂点を含み、2番目のツリーは残りの頂点を含みます。

これはO(log2n)時間で実行できることを知っています。複雑さ実装へのリンクはO(log2n)次のとおりです。https//code.google.com/p/self-balancing-avl-tree/

また、2つのAVLツリーをマージして、O(logn)時間で、一方のツリーのキーがすべて他方のキーよりも小さくなるようにする方法も知っています。以下は、複雑度実装O(logn)です。

def Merge(l, r) {
    if (!l || !r) 
        return l ? l : r;
    if (l->h <= r->h)
        r->l = Merge(l, r->l), Rebalance(r);
    else
        l->r = Merge(l->r, r), Rebalance(l);
}

回答:



-1

Let us define a function split(T,v) that takes in a tree, T and a value to split at, v. Suppose that each node of the tree stores its left child and right child in addition to the value at that node. Use the following algorithm:

  1. First we check to see if the input tree is simply a leaf or not.

  2. If T is not a leaf, compare the value of its root node, v' with v.

  3. If v' < v then recursively call split on the left subtree. Store the values of the recursive call as L' (returned left tree), R' (returned right tree), and r (option type indicated if the value v was found or not). Construct the new right tree, newR = Node(R',v',R), and return (L',r,newR).

  4. Else if v' > v then recursively call split on the right subtree. Store the values of the recursive call as L' (returned left tree), R' (returned right tree), and r (option type indicated if the value v was found or not). Construct the new left tree, newL = Node(L',v',L), and return (newL,r,R').

  5. Else if v' = v, return L, SOME(v), R.

  6. If T is a leaf, we must have reached the root of the tree without finding the input value v to split at. Return that you couldn't find the leaf by passing back NONE.

Why is this logarithmic? Well, you only ever traverse one root-to-leaf path of the tree, at most. We can easily reconstruct nodes in constant time since we're just re-assigning O(logn) references (in an imperative language) or reassigning O(logn) values that take a constant time to generate (in a functional language).

Here's the corresponding code for the algorithm. It's written in SML, but I'd be willing to clarify what anything means in the comments.

fun split(T,v) = case T of Leaf => (Leaf, NONE, Leaf) | Node(L,v,R) => case compare(v, v') of LESS => let val (L',r,R') = split(L,k) in (L',r,Node(R',r,R)) end | GREATER => let val (L',r,R') = split(R,k) in (Node(L',v',L),r,R') end | EQUAL => (L, SOME(v), R)

See this document for more details. It provides a more thorough explanation of the above.


This does not address the AVL balance conditions.
jbapple
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.