-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAVLTree.java
More file actions
64 lines (57 loc) · 1.57 KB
/
AVLTree.java
File metadata and controls
64 lines (57 loc) · 1.57 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
public class AVLTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
int height;
TreeNode(int val) { this.val = val; }
}
TreeNode root;
public void insert(int item) {
if (root == null) {
root = new TreeNode(item);
return;
}
TreeNode parent = binarySearchForPosition(item);
TreeNode node = new TreeNode(item);
node.height = 1;
if (item <= parent.val)
parent.left = node;
else
parent.right = node;
}
TreeNode binarySearchForPosition(int item) {
TreeNode current = root;
while (current != null) {
current.height++;
if (item <= current.val) {
if (current.left == null)
return current;
current = current.left;
} else {
if (current.right == null)
return current;
current = current.right;
}
}
return root;
}
public void printInOrder() {
printInOrder(root);
System.out.println();
}
void printInOrder(TreeNode node) {
if (node == null)
return;
printInOrder(node.left);
System.out.print(node.val + " ");
printInOrder(node.right);
}
public static void main(String[] args) {
AVLTree tree = new AVLTree();
for (int i = 0; i < 10; i++) {
tree.insert((int) (Math.random() * 10));
}
tree.printInOrder();
}
}