58 lines
975 B
Java
58 lines
975 B
Java
package bintree;
|
|
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
|
public class BinTreeSimple implements BinTree {
|
|
|
|
private static class Node {
|
|
final int value;
|
|
int occ;
|
|
Node left, right;
|
|
|
|
private Node(int value, int initOcc) {
|
|
this.value = value;
|
|
occ = initOcc;
|
|
}
|
|
}
|
|
|
|
private final Node root = new Node(0, 0);
|
|
|
|
public void insert(int value) {
|
|
Node n = root;
|
|
while (true) {
|
|
int nval = n.value;
|
|
if (value == nval) {
|
|
n.occ++;
|
|
return;
|
|
}
|
|
else if (value < nval) {
|
|
if (n.left == null) {
|
|
n.left = new Node(value, 1);
|
|
return;
|
|
}
|
|
n = n.left;
|
|
}
|
|
else { // value > nval
|
|
if (n.right == null) {
|
|
n.right = new Node(value, 1);
|
|
return;
|
|
}
|
|
n = n.right;
|
|
}
|
|
}
|
|
}
|
|
|
|
public int occurs(int value) {
|
|
Node n = root;
|
|
do {
|
|
int nval = n.value;
|
|
if (value == nval) {
|
|
return n.occ++;
|
|
}
|
|
n = (value < nval) ? n.left : n.right;
|
|
} while (n != null);
|
|
// value not found
|
|
return 0;
|
|
}
|
|
}
|