AVL tree--Data Structure

来源:互联网 发布:淘宝客费用 编辑:程序博客网 时间:2024/05/22 12:48

Height

Definition

The heightof a node is the maximum depth of its subtree.


AVL Property

AVL trees maintain the following property:

  For all nodesN|N.Left.HeightN.Right.Height| ≤ 1

We claim that this ensures balance. 

 

Conclusion

AVL Property

If you can maintain the AVL property, you can perform operations inO(log(n))time.



Insert:
If the balance is destroyed by adding a node, we need to insert nodes to be rebalanced.

AVLInsert(k,R)

Insert(k,R)
N Find(k,R)

Rebalance(N)

 

Rebalance(N)

P N.Parent
if N.Left.Height>N.Right.Height+1:

    RebalanceRight(N)
if N.Right.Height>N.Left.Height+1:

    RebalanceLeft(N)

AdjustHeight(N)
if P !=null:

    Rebalance(P)



AdjustHeight(N)

N.Height1+ maxN.Left.Height,  N.Right.Height)



If subtree too heavy, rotate right.


Delete:

AVLDelete(N)

Delete(N)
M Parent of node replacingN

Rebalance(M)


Summary

AVL trees can implement all of the basic operations inO(log(n))time per operation.



New operations:

Merge:

MergeWithRoot(R1,R2,T)

T.LeftR1
T .RightR2

R1.ParentT

R2.ParentT

return T

Time O(1)

Merge(R1,R2)

T Find(,R1)

Delete(T)

MergeWithRoot(R1,R2,T)

return T

Time O(h)

AVLTreeMergeWithRoot(R1,R2,T)

if |R1.HeightR2.Height| ≤1:

  MergeWithRoot(R1,R2,T)
  T .Htmax(R1.Height,R2.Height) +1

  return T



Split:

Split(R,x)

if R =null:

  return (null,null)

if x R.Key:
  (R1,R2)Split(R.Left,x)
  R3MergeWithRoot(R2,R.Right,R)

  return (R1,R3)

if x >R.Key:

  ...



Summary

Merge combines trees.
Split turns one tree into two.

Both can be implemented inO(log(n))time for AVL trees.