DSAA之伸展树(四)

1. 定义

  DSAA从时间复杂度引出了伸展树的定义:

  • a splay tree, that guarantees that any m consecutive tree operations take at most O ( m l o g n ) time.
  • Thus, a splay tree has O ( l o g n ) amortized cost per operation. Over a long sequence of operations, some may take more, some less.

  也就是说,伸展树保证任意次树的连续操作的平均时间复杂度为 O ( l o g n ) ,可能有一些操作时间复杂度多些,一些操作时间复杂度少些,但是从整体上来看,每个操作都能保证在 O ( l o g n ) 附近。伸展树克服了二叉搜索树的一些缺点:

  • the O(n) worst-case time per operation for binary search trees is not bad, as long at it occurs relatively infrequently. Any one access, even if it takes O(n), is still likely to be extremely fast.也就是说都由左子树或者右子树构成的二叉树最深节点的查找,时间复杂度为O(n),但是这是可以接受的,只要查找最深或者次最深节点的操作不要太频繁。
  • The problem with binary search trees is that it is possible, and not uncommon, for a whole sequence of bad accesses to take place. The cumulative running time then becomes noticeable.

  上面提到的二叉搜索树的缺点,并不常发生。因为数据组成成单单左子树或者右子树的情况并不多见,但是查找最深的节点或者次最深的节点的操作可能经常发生。为了解决这种情况,可以将经常访问的节点移到root上来,这样做的好处,可以保证连续m次操作的时间复杂度为 O ( l o g n ) ,具体的证明笔者就不关心了:

then it is clear that whenever a node is accessed, it must be moved. Otherwise, once we find a deep node, we could keep performing finds on it. If the node does not change location, and each access costs O ( n ) , then a sequence of m accesses will cost O ( m n ) .

  所以,伸展树提出的目的是保证连续多次访问二叉搜索树(包含极端情况)中较深子节点的平均时间复杂度(有资料叫均摊时间复杂度)为 O ( l o g n )

2. 伸展方法

  理解定义,就能理解方法,伸展树并不需要保存节点的高度或者其他的平衡信息,这在一定程度上简化了代码逻辑和复杂度,与AVL树的旋转一样,也要分情况讨论。
  
情况1:zig-zag
这里写图片描述

Here x is a right child and p is a left child (or vice versa). If this is the case, we perform a double rotation, exactly like an AVL double rotation.

  • 也就是x进行左右双旋转,(也就是x先与p进行右单旋,x再与g进行左单旋),没有打错,笔者喜欢在命名上看x的结合顺序命名双旋,但是code代码的时候,头脑要清晰,别调用错左右单旋函数。

情况2:zig-zig
这里写图片描述

Otherwise, we have a zig-zig case: x and p are either both left children or both right children. In that case, we transform the tree on the left of Figure 4.43 to the tree on the right.DSAA并没有指出来如何进行双旋

  • 观察可得,先g与p进行左单旋,p再与x进行左单旋

情况3:
这里写图片描述

  这个笔者补充的,因为伸展操作是沿着路径上操作每一个节点,总会遇到最后这种情况,RO是指root,此时只要进行一次左单旋或者右单旋(对称情况)就可以。

扫描二维码关注公众号,回复: 225547 查看本文章

猜你喜欢

转载自blog.csdn.net/lovestackover/article/details/80097327
今日推荐