-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalanceBinarySearchTree.java
128 lines (110 loc) · 2.59 KB
/
BalanceBinarySearchTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.ssm.controller.tree;
import java.util.Comparator;
/**
* 平衡二叉搜索树
*/
public class BalanceBinarySearchTree<E> extends BinarySearchTree<E>{
/**
*
*/
public BalanceBinarySearchTree() {
super(null);
}
/**
* 比较器
* @param comparator
*/
public BalanceBinarySearchTree(Comparator<E> comparator) {
super(comparator);
}
/**
*
*/
public void simpleRotate(
Node<E> r, //子树的根节点
Node<E> a, Node<E> b, Node<E> c,
Node<E> d,
Node<E> e, Node<E> f, Node<E> g
){
//d设置为子树的根节点,并且更新引用
d.parent = r.parent;
if(r.isLeftChild()){
r.parent.left = d;
}else if(r.isRightChild()){
r.parent.right = d;
}else{
rootNode = d;
}
//a-b-c
b.left = a;
if(a != null){
a.parent = b;
}
b.right = c;
if(c != null){
c.parent = b;
}
//e-f-g
f.left = e;
if(e != null){
e.parent = f;
}
f.right = g;
if(g != null){
g.parent = f;
}
//b-d-f
d.left = b;
d.right = f;
b.parent = d;
f.parent = d;
}
/**
* RR-左旋转
*/
public void rotateLeft(Node<E> grand){
//
Node<E> parent = grand.right;
Node<E> child = parent.left;
//
grand.right = child;
parent.left = grand;
//旋转操作
afterRotate( grand, parent, child);
}
/**
* LL-右旋转
*/
public void rotateRight(Node<E> grand){
//
Node<E> parent = grand.left;
Node<E> child = parent.right;
//
grand.left = child;
parent.right = grand;
//旋转操作
afterRotate( grand, parent, child);
}
/**
* 旋转操作
*/
public void afterRotate(Node<E> grand, Node<E> parent, Node<E> child){
//parent成为子树的根节点
parent.parent = grand.parent;
//祖先节点是左子树
if(grand.isLeftChild()){
grand.parent.left = parent;
//祖先节点是右子树
}else if(grand.isRightChild()){
grand.parent.right = parent;
}else{ //parent是根节点
rootNode = parent;
}
//更新child的parent
if(child != null){
child.parent = grand;
}
//更新grand的parent
grand.parent = parent;
}
}