2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * PURPOSE: Splay-Tree implementation
5 * FILE: lib/rtl/splaytree.c
9 /* INCLUDES *****************************************************************/
16 /* FUNCTIONS ***************************************************************/
24 PRTL_SPLAY_LINKS Links
37 PRTL_SPLAY_LINKS Links
,
38 PRTL_SPLAY_LINKS
*Root
51 PRTL_SPLAY_LINKS Links
64 PRTL_SPLAY_LINKS Links
76 RtlSplay(PRTL_SPLAY_LINKS Links
)
79 * Implementation Notes (http://en.wikipedia.org/wiki/Splay_tree):
81 * To do a splay, we carry out a sequence of rotations,
82 * each of which moves the target node N closer to the root.
84 * Each particular step depends on only two factors:
85 * - Whether N is the left or right child of its parent node, P,
86 * - Whether P is the left or right child of its parent, G (for grandparent node).
88 * Thus, there are four cases:
89 * - Case 1: N is the left child of P and P is the left child of G.
90 * In this case we perform a double right rotation, so that
91 * P becomes N's right child, and G becomes P's right child.
93 * - Case 2: N is the right child of P and P is the right child of G.
94 * In this case we perform a double left rotation, so that
95 * P becomes N's left child, and G becomes P's left child.
97 * - Case 3: N is the left child of P and P is the right child of G.
98 * In this case we perform a rotation so that
99 * G becomes N's left child, and P becomes N's right child.
101 * - Case 4: N is the right child of P and P is the left child of G.
102 * In this case we perform a rotation so that
103 * P becomes N's left child, and G becomes N's right child.
105 * Finally, if N doesn't have a grandparent node, we simply perform a
106 * left or right rotation to move it to the root.
108 * By performing a splay on the node of interest after every operation,
109 * we keep recently accessed nodes near the root and keep the tree
110 * roughly balanced, so that we achieve the desired amortized time bounds.
120 PRTL_SPLAY_LINKS NTAPI
121 RtlSubtreePredecessor (IN PRTL_SPLAY_LINKS Links
)
123 PRTL_SPLAY_LINKS Child
;
125 Child
= Links
->RightChild
;
129 if (Child
->LeftChild
== NULL
)
132 /* Get left-most child */
133 while (Child
->LeftChild
!= NULL
)
134 Child
= Child
->LeftChild
;
142 PRTL_SPLAY_LINKS NTAPI
143 RtlSubtreeSuccessor (IN PRTL_SPLAY_LINKS Links
)
145 PRTL_SPLAY_LINKS Child
;
147 Child
= Links
->LeftChild
;
151 if (Child
->RightChild
== NULL
)
154 /* Get right-most child */
155 while (Child
->RightChild
!= NULL
)
156 Child
= Child
->RightChild
;