This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw2/Ex1/src/bintree/BinTreeFullSyncEdited.java

72 lines
1.2 KiB
Java

package bintree;
public class BinTreeFullSyncEdited 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 synchronized int getOcc() {
return occ;
}
private synchronized void incrementOcc() {
occ++;
}
private synchronized Node goLeftOrNull(int value) {
if (this.left == null) {
this.left = new Node(value, 1);
return null;
}
return this.left;
}
private synchronized Node goRightOrNull(int value) {
if (this.right == null) {
this.right = new Node(value, 1);
return null;
}
return this.right;
}
}
private final Node root = new Node(0, 0);
public void insert(int value) {
Node n = root;
while (n != null) {
int nval = n.value;
if (value == nval) {
n.incrementOcc();
return;
}
else if (value < nval) {
n = n.goLeftOrNull(value);
}
else { // value > nval
n = n.goRightOrNull(value);
}
}
}
public int occurs(int value) {
Node n = root;
do {
int nval = n.value;
if (value == nval) {
return n.getOcc();
}
n = (value < nval) ? n.left : n.right;
} while (n != null);
// value not found
return 0;
}
}