树旋转包括两个不同的方式,分别是右旋转(以P为转轴)和左旋转(以Q为转轴)。两种旋转呈镜像,而且互为逆操作。
下图示意了两种树旋转过程中, 子树的初态和终态:
--- --- |Q||P| --- --- /\rightrotation/\ --- --- -------------> --- --- |P||Z||X||Q| --- --- <------------- --- --- /\leftrotation/\ --- --- --- --- |X||Y||Y||Z| --- --- --- ---
其中, 右旋转详细步骤如下图 R0, R1, R2 三个步骤所示, 左旋转则如 L0, L1, L2 三个步骤所示。
__ /\ --- / --- |Q|/|Q| --- --- --- / --- --- |P|/\R1|P|//\ --- |Q|R0 --- / --- -----> --- / --- R2|P| --- ----->/\/|Z|//|Z|-----> --- /\ --- --- --- --- --- --- /\ --- --- |X||Y||X||Y| --- --- |P||Z| --- --- --- --- |X||Q| --- --- __ --- --- /\/\/\ --- --- L2 --- \ --- L0 --- --- |X||Y|<-----|P|\|P|<-----|Y||Z| --- --- --- \ --- L1 --- --- --- --- /\\|Q|<-----/\|Q| --- \ --- --- \ --- |X|\\|X|\/\ --- --- --- --- --- --- |Y||Z||Y||Z| --- --- --- ---