Метод add для добавления элементов в MyTreeSet
This commit is contained in:
@@ -1,13 +1,12 @@
|
||||
package ru.spbstu.telematics.java;
|
||||
|
||||
/**
|
||||
* Hello world!
|
||||
*
|
||||
*/
|
||||
public class App
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
System.out.println( "Hello World!" );
|
||||
MyTreeSet<Integer> tree = new MyTreeSet<>();
|
||||
tree.add(10);
|
||||
tree.add(20);
|
||||
tree.add(5);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,4 +18,31 @@ public class MyTreeSet<E extends Comparable<E>> {
|
||||
public MyTreeSet() {
|
||||
root = null;
|
||||
}
|
||||
|
||||
public void add(E element) {
|
||||
if (root == null) {
|
||||
root = new Node(element);
|
||||
return;
|
||||
}
|
||||
|
||||
Node currentNode = root;
|
||||
Node parentNode = null;
|
||||
|
||||
while (currentNode != null) {
|
||||
int cmp = element.compareTo(currentNode.value);
|
||||
if (cmp == 0) {
|
||||
return;
|
||||
}
|
||||
parentNode = currentNode;
|
||||
currentNode = cmp < 0 ? currentNode.left : currentNode.right;
|
||||
}
|
||||
|
||||
Node newNode = new Node(element);
|
||||
|
||||
if (element.compareTo(parentNode.value) < 0) {
|
||||
parentNode.left = newNode;
|
||||
} else {
|
||||
parentNode.right = newNode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user