Метод size для MyTreeSet

This commit is contained in:
2025-02-03 18:45:06 +03:00
parent b40778d10c
commit 47427ae6fe
2 changed files with 22 additions and 0 deletions

View File

@@ -14,9 +14,15 @@ public class MyTreeSet<E extends Comparable<E>> {
}
private Node root;
private int size;
public MyTreeSet() {
root = null;
size = 0;
}
public int size() {
return size;
}
public boolean add(E element) {
@@ -26,6 +32,7 @@ public class MyTreeSet<E extends Comparable<E>> {
if (root == null) {
root = new Node(element);
size++;
return true;
}
@@ -47,6 +54,7 @@ public class MyTreeSet<E extends Comparable<E>> {
parentNode.right = newNode;
}
size++;
return true;
}
@@ -72,6 +80,7 @@ public class MyTreeSet<E extends Comparable<E>> {
}
if (!contains(element)) return false;
root = remove(root, element);
size--;
return true;
}

View File

@@ -58,4 +58,17 @@ class MyTreeSetTests {
assertThrows(NullPointerException.class, () -> myTreeSet.remove(null));
assertThrows(NullPointerException.class, () -> treeSet.remove(null));
}
@Test
void testSize() {
assertEquals(myTreeSet.size(), treeSet.size());
treeSet.add(15);
myTreeSet.add(15);
assertEquals(myTreeSet.size(), treeSet.size());
treeSet.add(50);
myTreeSet.add(50);
assertEquals(myTreeSet.size(), treeSet.size());
assertEquals(myTreeSet.remove(50), treeSet.remove(50));
assertEquals(myTreeSet.size(), treeSet.size());
}
}