rendered paste bodyWHILE:
/**
* Insert a new item in tree.
* @param x the item to insert.
*/
public void insert(E x) {
BinaryNode<E> newNode = new BinaryNode<E>(x);
if (root == null) {
root = newNode;
} else {
BinaryNode<E> y = root;
boolean inserted = false;
while(!inserted) {
if (y.getElement().compareTo(x) > 0) {
if(y.getLeft() == null) {
y.left = newNode;
inserted = true;
} else {
y = y.getLeft();
}
} else {
if(y.getRight() == null) {
y.right = newNode;
inserted = true;
} else {
y = y.getRight();
}
}
}
}
}
REKURSIVT:
/**
* Insert a new item in tree.
* @param x the item to insert.
*/
public void insert(E x) {
if(root == null) //for empty trees
root = new BinaryNode<E>(x);
else
insert(x, root);
}
/* Insert the element x into the subtree with root n */
private void insert(E x, BinaryNode<E> n) {
if (n.getElement().compareTo(x) > 0) {
if(n.getLeft() == null) {
n.left = new BinaryNode<E>(x);
} else {
insert(x, n.getLeft());
}
} else {
if(n.getRight() == null) {
n.right = new BinaryNode<E>(x);
} else {
insert(x, n.getRight());
}
}
}