-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAVLTree.java
More file actions
119 lines (94 loc) · 2.63 KB
/
AVLTree.java
File metadata and controls
119 lines (94 loc) · 2.63 KB
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
package data.structures;
public class AVLTree {
private int key, height;
private AVLTree left, right;
public static final AVLTree NIL = new AVLTree();
private AVLTree() {
left = right = this;
height = -1;
}
AVLTree(int key) {
this.key = key;
left = right = NIL;
}
AVLTree(int key, AVLTree left, AVLTree right) {
this.key = key;
this.left = left;
this.right = right;
height = 1 + Math.max(left.height, right.height);
}
public int size() {
if (this == NIL) return 0;
return 1 + left.size() + right.size();
}
@Override
public String toString() {
if (this == NIL) {
return "";
}
return left + " " + key + " " + right;
}
public boolean add(int key) {
int oldsize = size();
grow(key);
return size() > oldsize;
}
private AVLTree grow(int key) {
if (this == NIL) return new AVLTree(key);
if (key == this.key) return this;
if (key < this.key)
left = left.grow(key);
else
right = right.grow(key);
rebalance();
height = 1 + Math.max(left.height, right.height);
return this;
}
private void rebalance() {
if (right.height > left.height + 1) {
if (right.left.height > right.right.height)
right.rotateRight();
rotateLeft();
}
if (left.height > right.height + 1) {
if (left.right.height > left.left.height)
left.rotateLeft();
rotateRight();
}
}
private void rotateLeft() {
left = new AVLTree(key, left, right.left);
key = right.key;
right = right.right;
}
private void rotateRight() {
right = new AVLTree(key, left.right, right);
key = left.key;
left = left.left;
}
public int getRoot() {
return key;
}
public void setRoot(int key) {
this.key = key;
}
public AVLTree getLeft() {
return left;
}
public void setLeft(AVLTree left) {
this.left = left;
}
public AVLTree getRight() {
return right;
}
public void setRight(AVLTree right) {
this.right = right;
}
public static void main(String[] args) {
AVLTree avl = new AVLTree(1);
avl.add(2);
avl.add(4);
avl.add(3);
System.out.println(avl.toString());
}
}