Advanced data structures (a)

A . Top-down tree extending

Splay trees taking into account the principle of locality, the entire seek time is less, the node will be frequently adjusted to find the root, i.e., by changing the tree structure, so that it maintains the operation of O (logN) time boundaries amortization .

Stretching single tree, the rotation diagram of a zigzag-shaped rotation and following rotation,

 

FIG rotating a schematic diagram of a single rotation of splay trees 1-1, a zigzag shape and rotating the rotary expansion

After the last step in deployment, the need for L, R and the intermediate tree merge to form a single tree, the combined diagram below

FIG. 1-2 splay trees merge is performed after completion of stretching

Splay trees top-down deployment following code,

FIG. 1-3 splay trees top-down expansion code

Stretch tree node on the location of the most recent search of easy search of the root node, let it be applied in many environments, such as network applications, some fixed content will be a large number of repeat visits. Splay trees can make this repeat the search with very high efficiency completed.

Two . Red-black tree

Red-black tree is a self-balancing binary search tree, and the like AVL tree, the tree is balanced so that during the insertion and deletion operations by the specific operation, so as to obtain higher lookup performance.

Red-black tree features:

(1) Each node is either black or red.

(2) the root is black.

(4) If a node is red, then its child nodes must be black.

(5) from any node to all leaves of each path contains the same number of black nodes.

FIG. 2-1 is a conventional red-black tree

Find in red-black trees do not need to modify their operations, but in the insert and delete operations, the nature of the red-black tree may be damaged, we need to restore the red-black properties, but the time complexity of the operation remains at its insertion and deletion O (log n), but these operations are somewhat complicated.

The red-black tree insertion and deletion can be extended to the tree top-down manner.

设当前节点为Current,其兄弟节点为Brother,父节点为Parent,祖父节点为Grand,曾祖父为Great(空节点的默认颜色是黑色)。

在自顶向下的插入过程中,若Current节点有两个红孩子时,进行颜色翻转(使Current为红,其两孩子为黑,不管Current是否为根,都令根为黑)。

颜色翻转后,若Current的父节点Parent为红,则进行旋转。

自顶向下的插入操作实现代码如下,

2-2 红黑树自顶向下的插入过程

在自顶向下的删除过程中,与AVL树同样将删除非叶子节点转换为删除叶子节点,具体过程如下

第一步,检查根,并将根变为红色,

1. 若根有两个黑儿子,向下并进入第二步

2. 其他则进入第二步B情况

第二步,

A情况,当前节点Current有两个黑儿子

A1.兄弟节点Brother节点也有两个黑儿子,翻转Current、Parent和Brother节点的颜色,向下(示意图如下)

2-3 红黑树自顶向下删除A1的情况

A2.兄弟节点Brother节点的左儿子为红,进行之字形旋转,并翻转Current和Parent颜色,向下(示意图如下)

2-4 红黑树自顶向下删除A2的情况

A3.兄弟节点Brother节点的右儿子为红,进行一字形旋转,并翻转Current、Parent、Brother和Brother右儿子节点的颜色,再向下(示意图如下)

2-5 红黑树自顶向下删除A3的情况

B情况,当前节点Current至少有一个红儿子,

Current节点继续向下,若新的Current节点为红,继续向下。若新的Current节点为黑,则单旋转Brother节点和Parent节点,同时翻转Brother和Parent节点,回到第二步;

第三步,最终找到要删除节点,这是一个叶节点,将节点以红节点身份删除,否则转换为删除叶子节点;

第四步,将根恢复为黑色。

 

Guess you like

Origin www.cnblogs.com/lincz/p/11141838.html