3
3
*/
4
4
package akc170000 ;
5
5
6
- import java .util .Comparator ;
7
-
8
6
public class AVLTree <T extends Comparable <? super T >> extends BinarySearchTree <T > {
9
7
static class Entry <T > extends BinarySearchTree .Entry <T > {
10
8
int height ;
@@ -14,6 +12,8 @@ static class Entry<T> extends BinarySearchTree.Entry<T> {
14
12
}
15
13
}
16
14
15
+
16
+
17
17
// LL >> R(x)
18
18
private BinarySearchTree .Entry case1 (BinarySearchTree .Entry x ){
19
19
BinarySearchTree .Entry y = x .left ;
@@ -51,23 +51,37 @@ private BinarySearchTree.Entry case4(Entry x){
51
51
z .left = x ;
52
52
return z ;
53
53
}
54
+
54
55
AVLTree () {
55
56
super ();
56
57
}
57
58
59
+ private void fixAVL (){
60
+
61
+ while (!parentStack .isEmpty ()) {
62
+ BinarySearchTree .Entry parent = parentStack .pop ();
63
+ get (parent ).height = 1 + Math .max (get (parent .left ).height , get (parent .right ).height );
64
+ int leftHeight = parent .left == null ? -1 : get (parent .left ).height ;
65
+ int rightHeight = parent .right == null ? -1 : get (parent .right ).height ;
66
+ if (Math .abs (rightHeight - leftHeight ) > 1 ){
58
67
59
- private void fixAVL (BinarySearchTree .Entry x ){
60
- BinarySearchTree .Entry parent = parentStack .pop ();
68
+ }else {
69
+ break ;
70
+ }
71
+
72
+ }
73
+ }
74
+
75
+ Entry get (BinarySearchTree .Entry x ){
76
+ return (Entry ) x ;
61
77
}
62
78
63
79
@ Override
64
- public boolean add (T k ) {
80
+ public boolean add (T k ){
65
81
BinarySearchTree .Entry x = new BinarySearchTree .Entry (k ,null ,null );
66
82
((Entry ) x ).height = 0 ;
67
83
if (super .add (x )){
68
- BinarySearchTree .Entry p_t = parentStack .pop (); // parent of the node x
69
- BinarySearchTree .Entry g_t =parentStack .pop (); // grand parent of node x
70
-
84
+ fixAVL ();
71
85
return true ;
72
86
}else {
73
87
// adjust the height of current node
0 commit comments